javascripthtmltagged-templates

ES6: tagged templates for nested html tags


I'm newly learning JavaScript and experimenting its tagged template literals.

<p> Handlebars? Tagged template literals? <span> That is a question. </span> </p>

Above is HTML code. I want to achieve with below code the similar outcome but allow the possibility that be able to replace the variables str and quote as arrays.

str = 'Handlebars? Tagged template literals?'
quote = 'That is a question.'

const renderMe = htmlString
`<p>
  ${str}
      <span>
        ${quote}
      </span>
</p>`

function htmlString(string, ...exp1) {
  return () => {
    const p = document.createElement("p")
    p.textContent = exp1[0]

    const span = document.createElement("span")
    span.textContent = exp1[1]

    return p  //but how about span???
  }
}

document.body.appendChild(renderMe())

As you can see, I'm stuck at the return stage. So what can be done to improve the code?


Solution

  • You simply need to append span to p, after setting the content:

    function htmlString(string, ...exp1) {
      return () => {
        const p = document.createElement("p")
        p.textContent = exp1[0]
    
        const span = document.createElement("span")
        span.textContent = exp1[1]
    
        p.appendChild(span)
    
        return p
      }
    }
    

    Hope this helps :)