Ciao
i have some xHTML like this:
<!DOCTYPE html>
<html>
// [ wellformed xHTML here ]
</html>
<!-- a comment here -->`
I would get the text string inside the last comment: "a comment here". Note: it's outside main html tag.
I can log it in console trying:
var goal = document.getElementsByTagName('html')[0].parentNode.childNodes; console.log(goal);
... goal.lenght is 3, and finally goal[2] .textContent should contain the string "a comment here",
but i tried yet with .nodeValue, innerHTML etc, also converting to array, and all return undefined...
Comments are anonymous, you cannot read them anywhere except your code editor, and that’s the whole point.
Aside from comments not being designed to be readable by JavaScript, you can still see them in their parent node’s innerHTML.
A simple way to do this is:
Here’s a simple script that will get all of the comments from the entire page:
function filterNone() {
return NodeFilter.FILTER_ACCEPT;
}
function getAllComments(rootElem) {
var comments = [];
// Fourth argument, which is actually obsolete according to the DOM4 standard, is required in IE 11
var iterator = document.createNodeIterator(rootElem, NodeFilter.SHOW_COMMENT, filterNone, false);
var curNode;
while (curNode = iterator.nextNode()) {
comments.push(curNode.nodeValue);
}
return comments;
}
// Wait until the window is done loading
window.addEventListener("load", function() {
console.log(getAllComments(document.body));
});