spinners
spinners

Reputation: 2679

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

Upvotes: 4

Views: 2886

Answers (3)

dfsq
dfsq

Reputation: 193271

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/

Upvotes: 8

SVSchmidt
SVSchmidt

Reputation: 6537

You can get all the comments using a function like this:

var $comments = [];
$("*").contents().filter(function() {
    return $(this)[0].nodeName == "#comment";
}).each(function() {
    $comments.push($(this));
});

console.log($comments);

http://jsfiddle.net/Whre/Zjj3n/

Unfortunately, I do not understand what you mean by

wrap them in a div/span where they are sitting in the document

If the comment belongs to the next element, you could directly apply it to the element: http://jsfiddle.net/Whre/Zjj3n/3/

Upvotes: 1

doniyor
doniyor

Reputation: 37896

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);
    });
});

Upvotes: 8

Related Questions