javascript – Get commented content from html

Question:

The question is this. Let's say the site has some pieces of html that are commented. For example like this <!--<div>text</div>-->

Is it possible with the help of javascript to take these pieces and use them like that?

But it is not necessary to give any separate libraries. I do not want to attach some other library with hundreds of lines to the site for this.

And parsing with regular expressions is not at all interesting, because then the selected nodes will be just string and it will not be possible to work with them separately.

Here is an example html code.

<div id="image-container">
    <!--
    <img src="http://lorempixel.com/200/100/animals/1" width="200" height="100">
    <img src="http://lorempixel.com/200/100/animals/2" width="200" height="100">
    -->
</div>
<div id="container"></div>

Answer:

Yes, but as a string

function enumDom() {
  var div = document.getElementById('image-container');
  for (var i = 0; i < div.childNodes.length; i++) {
    if (div.childNodes[i].nodeType == 8)  // NODE_COMMENT
      console.log(div.childNodes[i].nodeValue);
  }
}
<div id="image-container">
    <!--
    <img src="http://lorempixel.com/200/100/animals/1" width="200" height="100">
    <img src="http://lorempixel.com/200/100/animals/2" width="200" height="100">
    -->
</div>
<div id="container"></div>
<button onclick="enumDom()">Enum</button>

How to parse such a line – see for yourself. jQuery will handle this.

Why such perversion? Wouldn't it be easier to just make these elements invisible?

If you need to upload images, then do this

function showImage() {
  var div = document.getElementById('image-container');
  for (var i = 0; i < div.children.length; i++) {
    var img = div.children[i];
    img.src = img.attributes['data-src'].value;
    img.style.display = 'inline';
  }
}
#image-container img {
  display: none;
}
<div id="image-container">
    <img data-src="https://multator.ru/preview/uximrdanemqi" width="200" height="100">
</div>
<div id="container"></div>
<button onclick="showImage()">Show</button>
Scroll to Top