简体   繁体   中英

Javascript pull content from variable by id

I am trying to pull content inside a variable using plain java script. I am trying to get only part of the variable with an id. In this example I am trying to pull only part of html with id 'container'.

My fiddle https://jsfiddle.net/a2ngc9jv/2/

var htmlPage = `
<html>
<div>
testing but not required
</div>
  <div id="container">
    <p>
     i want to pull this whole block from parent 
    </p>
    <p>
      test 2
    </p>
  </div>

</html>`;

console.log(htmlPage.getElementById("container"))
console.log(document.getElementById("container"))

htmlPage is a string not a document node. However it's easy to put it into one:

 var htmlPage = ` <html> <div> testing but not required </div> <div id="container"> <p> i want to pull this whole block from parent </p> <p> test 2 </p> </div> </html>`; // it might not be "allowed" to put a html tag inside a div but it works for this purpose. var n = document.createElement('div'); n.innerHTML = htmlPage; var content = n.querySelector('#container p:first-child').innerHTML; console.log(content); 

If you're in the Browser you can use DOMparser() to turn this into a real dom object, then you can call the method you want to get elements from it.

 var htmlPage = ` <html> <div> testing but not required </div> <div id="container"> <p> i want to pull this whole block from parent </p> <p> test 2 </p> </div> </html>`; var parser=new DOMParser(); var htmlDoc=parser.parseFromString(htmlPage, "text/html"); console.log(htmlDoc.getElementById("container")) console.log(htmlDoc.getElementById("container").innerHTML) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM