Is it possible to generate final comments for html

Is it possible to create comments for closing div tags, lets take this ex. regular HTML into account :

<div id="content">
...
...buch of html or whateve
</div>

with comments:

<div id="content">
    ...
    ...buch of html or whateve
    </div><!--End of content-->

etc. go through each div element and comment on its end?

+3
source share
3 answers
var divs = document.getElementsByTagName("div");
for (var d = divs.length-1; d >= 0; --d) {
   var div = divs[d];
   var id = div.id;  // d.getAttribute("id")
   if (id) {
     var cmt = document.createComment("End of " + id);
     div.parentNode.insertBefore(cmt, div.nextSibling);
   }
}
0
source

using jQuery is very simple.

jQuery('div').after('<!--end of content-->');

EDIT:

jQuery('div').each(function(){ jQuery(this).after('<!-- end of '+jQuery(this).id + '-->');});
+1
source

PHP DOM:
PHP , ; DOM, , .
(, , , JS)

$html = <<<HTML
<div id="content">
...
...buch of html or whateve
</div>
HTML;

$dom = new DOMDocument();
$dom->loadHTML($html);
$divs = $dom->getElementsByTagName('div');
for ($i = $divs->length - 1 ; $i > -1 ; $i--) {
    $div = $divs->item($i);
    if ($div->hasAttribute('id')) {
        $id = $div->getAttribute('id');
        $comment = $dom->createComment("End of {$id}");
        if($div->nextSibling) {
            $div->parentNode->insertBefore($comment, $div->nextSibling);
        } else {
            $div->parentNode->appendChild($comment);
        }   
    }
}
echo $dom->saveHTML();


HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<div id="content">
...
...buch of html or whateve
</div>
<!--End of content-->
</body></html>


:

  • DOM allows you to load and parse invalid HTML
  • And generates valid-HTML


And what it does:

  • Download the HTMl string using DOMDocument
  • Search all tags <div>
  • Forerunner tag <div>:
    • If he has attributes id,
    • Get value
    • Create a comment based on this value
    • And add it to the DOM after the tag </div>

Another solution, thinking about this, would probably be to use XPath instead of getElementsByTagName+ hasAttribute...

+1
source

Source: https://habr.com/ru/post/1736789/


All Articles