Created
March 25, 2014 10:29
jQuery Comments() Plug-in To Access HTML Comments For DOM Templating
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This jQuery plugin will gather the comments within | |
// the current jQuery collection, returning all the | |
// comments in a new jQuery collection. | |
// | |
// NOTE: Comments are wrapped in DIV tags. | |
jQuery.fn.comments = function( blnDeep ){ | |
var blnDeep = (blnDeep || 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){ | |
// We found a comment node. Add it to | |
// the nodes collection wrapped in a | |
// DIV (as we may have HTML). | |
jComments = jComments.add( | |
"<div rel='" + strParentID + "'>" + | |
objChildNode.nodeValue + | |
"</div>" | |
); | |
} else if ( | |
blnDeep && | |
(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 ); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> | |
<html> | |
<head> | |
<title>Untitled</title> | |
<script type="text/javascript" src="jquery-1.3.2.js"></script> | |
<script type="text/javascript" src="jquery.comments.js"></script> | |
<script type="text/javascript"> | |
$( | |
function(){ | |
// Find all comments within the given collection. | |
var jComments = $( "#template" ).comments(); | |
// Add the template text to list. | |
$( "#list" ).append( jComments.html() ); | |
$( "#list" ).append( jComments.html() ); | |
$( "#list" ).append( jComments.html() ); | |
} | |
); | |
</script> | |
</head> | |
<body> | |
<!--- Here is a place-holder list. ---> | |
<ul id="list" /> | |
<div id="template" style="display: none ;"> | |
<!-- | |
<li>This is an LI template.</li> | |
--> | |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment