Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to find all comments in a HTML document and wrap them in a div?

I'm working with a third party system that renders content into a html document like this:

<!-- componentID: 1234 -->
<div class="some-class"> .... </div>

<!-- componentID: 1235 -->
<div class="another-class"> .... </div>

So the system renders that componentId into a comment. The system sadly provides no way for me to pass that id as a data attribute. I am currently stuck with this.

Is it possible to find all these comments and wrap them in a div/span where they are sitting in the document? I could then access that string and grab the id with regex.

Thanks

like image 258
spinners Avatar asked Dec 02 '22 19:12

spinners


2 Answers

try this, it grabs all comments in html file. if there is no other unrelated comments to your plan, this can do the job.

$(function() {
    $("*").contents().filter(function(){
        return this.nodeType == 8;
    }).each(function(i, e){
        alert(e.nodeValue);
    });
});
like image 100
doniyor Avatar answered Jan 12 '23 01:01

doniyor


I will post non jQuery solution and much more efficient then traversing the whole DOM tree:

var x = document.evaluate('//comment()', document, null, XPathResult.ANY_TYPE, null),
    comment = x.iterateNext();

while (comment) {
    alert(comment.textContent);
    comment = x.iterateNext();
}

However this solution is not for IE, which doesn't implement document.evaluate methods, that's why be aware and use it only if you don't have to support IE.

Demo: http://jsfiddle.net/z6GU3/

like image 44
dfsq Avatar answered Jan 12 '23 01:01

dfsq