Development
Created on:
Thursday, December 1, 2016

How to select HTML comments with jQuery

Below is the jQuery plugin code snippet

jQuery.fn.comments = function( isDeep ){
  var
isDeep = isDeep||false;
  var jComments = $( [] );

 // Loop over each node to search its children for
 // comment nodes and element nodes (if deep search).
  this.each(
    function( intI, objNode ){
      var objChildNode = objNode.firstChild;
      var strParentID = $(this).attr('id');

     // Keep looping over the top-level children
     // while we have a node to examine.
      while (objChildNode){

       // Check to see if this node is a comment.
        if (objChildNode.nodeType === 8){
         jComments = jComments.add("<div rel='" + strParentID + "'>" + objChildNode.nodeValue + "</div>");
       }
        else if (isDeep && (objChildNode.nodeType === 1)) {
         // Traverse this node deeply.
         jComments = jComments.add($( objChildNode ).comments( true ));
       }
       // Move to the next sibling.
        objChildNode = objChildNode.nextSibling;
       }
     }
   );

    // Return the jQuery comments collection.
    return( jComments );
};

Stop blending in with the rest of the crowd &
start leaving your mark on the web.
Your success is our success

Let's work together