Selecting HTML comments with jQuery

JqueryHtml

Jquery Problem Overview


Does any one know how to select HTML comment nodes 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"></script>
    <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.

Jquery Solutions


Solution 1 - Jquery

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

Solution 2 - Jquery

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

var comments = $( "#foo" ).comments();
alert(comments.html());

Solution 3 - Jquery

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.

Solution 4 - Jquery

Once again, I'm late in the game, but I thought I'd contribute back as I found this post helpful in a recent situation I faced.

In our context, we have an ad service delivering blocks of code to render the ad.

Each ad has unique 'flight id'. Meaning the same 250x300 side rail ad can have multiple flights. So in one impression, you might see an ad for Subway, refresh and perhaps Quizno's.

Unfortunately, the service delivers this flight ID in a comment, and not as something a bit more useful like a data-attribute. That said, each comment is within a

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnthony JohnstonView Question on Stackoverflow
Solution 1 - JqueryFrank GeuekeView Answer on Stackoverflow
Solution 2 - Jquerykarim79View Answer on Stackoverflow
Solution 3 - JqueryMikeView Answer on Stackoverflow
Solution 4 - JqueryTimothy PetrakisView Answer on Stackoverflow