Is there any way to interact with HTML comments via JS?

<div><!--Камент-->простотекст</div> 

Ps do not say that it is better to use display: none. I'm just purely theoretically interested in the interaction with the comments.

  • I think so, no need to close the answered questions. HashCode, like its ideological dad StackOverflow, is, after all, a wiki. Perhaps, after some time, something will change - then someone will come and add new information. - drdaeman
  • one
    Okay, I will not. ^^ - knes
  • @drdaeman, why then close the option with the option ("Answer received and accepted")? What is the essence of the closing? They do not disappear anywhere? - Chad

2 answers 2

Here is an example. jquery there is not mandatory, so for imaginary convenience.

With your permission:

 <div><!--comment 1-->text3<span>test</span><!--comment2--></div> 

Js:

 $(document).ready(function(){ $("div").each(function(){ child = this.firstChild; while (child){ // determine the type of the node switch (child.nodeType){ // if the node is a comment node, output its value case Node.COMMENT_NODE : alert(child.nodeValue); break; } // move to the next child node child = child.nextSibling; } }); }); 
  • one
    I have nothing against jQuery. :) For anyone against, there is a label [pure_js] [1] [1]: hashcode.ru/questions/tagged/pure_js - knes
  • I actually tried to find out if jquery could work on the comments - I couldn't. as a piece of html I see ($ ("div"). html () will give comments to this example), but it cannot work as a query ($ (child). text () returns null, and replaceWith will not work either)). - Chad
  • @knes, I am categorically against multiplying entities without need, i.e. tag [pure_js] . - karmadro4
  • No need, no one offers. However, the JS tag cannot fully convey to the question that answers the specifics. Ardent opponents of using frameworks now have a real opportunity to filter what they don’t want to see. Those who want a solution to the problem write js, who want a solution on jquery (or other frameworks), writes them, except for generalizing js. Those who do not want to contact third-party libraries, pay attention to this fact with the tag described above. - knes
  • @knes, this will not work. Those who are interested in [javascript] (just like that, not [js] ) and do not ignore (for example) [jquery] still read the question. Indeed, what kind of purism can we talk about, if in 95% of cases JavaScript is associated with a specific DOMImplementation? - karmadro4

damn, did not have time:

  $('div').contents().each(function(){ if(this.nodeType == Node.COMMENT_NODE) { console.log(this.data); } }); 
  • It had time. = Kommersant Although, that answer is more detailed and answers the question a little more. - knes