Monday, August 23, 2010

HTML Comments as strings

Reading HTML comments from a DOM tree with JavaScript is easy.

var nodes = document.body.childNodes,
comments = [];

for (var i = 0; i < nodes.length; i++) {

// if the nodeType is 8
if (nodes[i].nodeType == 8) {

// this is a comment
comments.push(nodes[i]);
}
}

Let's say that the comments array is not empty, so the type of comments[0] is a Comment. That's great but how can you read its content?

This is what the W3C DOM-Level-1 spec says. It implements the Comment interface.

interface Comment : CharacterData {
};

This does not really help us but don't despair. It also implements the Node interface.

...
readonly attribute DOMString nodeName;
attribute DOMString nodeValue;
...

Yes, it's read-only but you can get the comment as a string by using its nodeValue.

comments[0].nodeValue


W3C DOM-Level 3 specifies something called textContent. This can also do the job, you can read about them here, textContent vs. innerText

3 comments:

  1. Are you trying to earn money from your traffic with popunder advertisments?
    In case you are, have you considered using Clickadu?

    ReplyDelete
  2. The issue of bringing amendments in the no-detention policy is also on the agenda of the CABE meeting. Cbseresults.nic.in/, cbseresults.nic.in, www.cbseresults.nic.in

    ReplyDelete

  3. Over the last few days, several SSC result dates have been doing the rounds on social media. Putting these rumours to rest, MSBSHSE has issued a statement, saying, "The State board has yet not declared any date for declaring the result of SSC. Yet, there are different dates being circulated on social media. None of those are official and hence, students and parents should not believe them. We will declare the SSC result in the next week."

    MahResulT.nic.in, www.mahresulT.nic.in, Maha Board Result, maha board result, MAH HSC RESULTS, MAH BOARD SSC RESULTS

    ReplyDelete