简体   繁体   中英

JavaScript Comment Node and parsing the HTML

I'm working with Nodes and comments in html. Is there a way without any plugin to parse the HTML inside of a comment?

I can currently use the nodeValue method but that only returns a string.

Even getting attributes in a element inside a comment would be helpful.

You can do regex matching on the comment content (the string). Even one more option : put a valid JSON string in the comment, and later turn it into a valid JS object using JSON.parse() .

Using nodeValue is good to go. Please review this one:

 function log(str) { document.body.innerHTML += str + '<br>'; } var x = Array.from(document.body.childNodes); x.forEach(function(el) { if (el.nodeType === 8) { var div, elm; div = document.createElement('div'); log(el.nodeValue); div.innerHTML = el.nodeValue; //here we get element we need elm = div.children[0]; console.log(elm.nodeName, "id = " + elm.getAttribute('id')); } }) 
 <!-- <select id="testid"> <option value="1">text1</option> <option value="2">text2</option> <option value="3">text3</option> </select> --> 

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