tags:

views:

540

answers:

3

Does any one know how to select html comments with jquery?

<html>
<head>
    <title>Check Test</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;
    <script type="text/javascript">
        $(function() {
            $("body *").each(function() {
                alert($(this).wrap("<span />").parent().html());
            });
        });
    </script>
</head>
<body>
    <!-- Hello -->  
    <p>
        <label for="thing">Thing Label</label>
        <input id="thing" type="checkbox" />
    </p>

This doesn't pick up the comment

+1  A: 

There's the jQuery comments() plugin which will do that for you. Usage:

var comments = $( "#foo" ).comments();
alert(comments.html());
karim79
I really need to be able to select the comments in the same way as any other element, but thats a good start, thank you
Anthony Johnston
+1  A: 

And if you don't want a plugin:

var content = jQuery('body').html();
alert(content.match(/<!--.*?-->/g));

This uses regular expressions. It is set to search for anything enclosed by <!-- and --> while it doesn't matter what's written on the inside.

NOTE: I am not sure however, if jQuery also returns comments. If it does not, this approach does not work.

Mike
It does return comments, so the above works, thanks for the suggestion
Anthony Johnston
Actually looking again, this is not realy using jquery to do anything useful ie document.body.innerHTML == jQuery('body').html(), and there is more to the regex than suggested here... thinking again, thanks anyway Mike
Anthony Johnston
+1  A: 

This seems to do something equivalent to what you're looking for:

    $(function() {
        $("body").contents().filter(function(){
            return this.nodeType == 8;
        }).each(function(i, e){
            alert(e.nodeValue);
        });
    });
Frank Geueke
+1 for using native DOM properties.
Sean Vieira