JiaLin Wang
JiaLin Wang

Reputation: 13

How do I convert string to html and insert into certain dom element?

I was trying to convert string to html and insert into a dom element by using Domparser but the html can't be assign with any css, and it works fine with JQuery.I wonder why? console

    var ctn = document.body.querySelector('.container')
    var popupHTML = `
      <div class="bx-popup-ctn">
        <div class="bx-popup-header-ctn">header</div>
        <div class="bx-popup-content-ctn">
          <div class="bx-popup-content">  
            content
          </div>
        </div>
      </div>
    `
    // 1.using DOMParser
    popupHTML = new DOMParser().parseFromString(popupHTML,"text/xml")
    popupHTML = popupHTML.querySelector('.bx-popup-ctn')
    ctn.append(popupHTML)
    // 2. using JQuery
    // $(".container").append(popupHTML)

Upvotes: 0

Views: 578

Answers (1)

fabrv
fabrv

Reputation: 382

There is no need to parse the HTML before adding it to the DOM. You can append HTML in pure JS like you would treat any normal string.

ctn.innerHTML = ctn.innerHTML + popupHTML

Here's a link that you might find useful https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML

Upvotes: 1

Related Questions