Here is a possible solution, in PHP, using DOM :
Using PHP allows you to save it, or whatever you need to ; and as it's using DOM, which is quite standardized, translating this to another language shouldn't require too much work.
(And, judging from a comment on your question, you didn't exclude other languages that 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();
Which gets you the following HTML source :
<!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>
A couple of things to note :
- DOM allows one to load and parse non-valid HTML
- And generates valid-HTML
And, about what this does :
- Load the HTMl string, using
DOMDocument
- Search for all
<div>
tags
- Foreach
<div>
tag :
- If it has an
id
attributes,
- Get its value
- Create a comment based on that value
- And add it to the DOM, after the
</div>
tag
Another solution, thinking about it, would probably have been to use XPath, instead of getElementsByTagName
+ hasAttribute
...