Menu
I want to find any <!– –> comment tags in a page and then read the contents. I would also like to distinguish between those in the body and those elsewhere in the HTML document.
What do I use to get an array of these elements?
[CODE]var els = document.getElementsByTagName( "*" );
for ( var i = 0, length = els.length; i < length; i++ ) {
[B]if ( els[i].nodeName === "#comment" ) {[/B]
// it's a comment node
}
}[/CODE]
[CODE]<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!-- First comment in the head-->
<!-- This comment is in the head and takes up
a couple of lines -->
<title>Get Comments</title>
<script type="text/javascript">
/* A javascript comment */
// A second javascript comment.
function init(){
var comments = [];
var regCom1 = //{2}[^n]+|/*[sS]+*/n/g;
var walkDom = function (node){
node = node.firstChild;
while (node){
walkDom(node);
isComment(node);
node = node.nextSibling;
}
}
// And a third javascript comment.
function isComment(node){
if (node.nodeType === 8){
comments[comments.length] = node.parentNode.nodeName+' - '+node.data.replace(/[nr]/g,"");
} else if (node.data && node.parentNode.nodeName === "SCRIPT") {
var temp = node.data.match(regCom1);
for (var i = 0, len = temp.length; i < len; i++){
temp[i] = temp[i].replace(/^/{2}s+|^/*s+|(*/[nr])/g,"")
comments[comments.length] = node.parentNode.nodeName+' - '+temp[i];
}
}
return;
}
walkDom(document);
var output = "";
for (var i = 0, len = comments.length; i < len; i+=1){
output+=comments[i]+'n';
}
alert (output);
}
window.onload = init;
</script>
</head>
<body>
<!-- First comment in the body -->
<div>
<!--
This comment
is in a DIV element
and takes up
a few lines
-->
</div>
</body>
</html>[/CODE]
I want to find any <!-- --> comment tags in a page and then read the contents. I would also like to distinguish between those in the body and those elsewhere in the HTML document.
What do I use to get an array of these elements?[/QUOTE]
[CODE]
//public domain
function getNodes(prop, val, meth, nd, useSelf ){
var r=[], any= getNodes[val]===true;
nd=nd||document.documentElement;
if(nd.constructor===Array){nd={childNodes:nd};}
for(var cn=nd.childNodes, i=0, mx=cn.length;i<mx;i++){
var it=cn[i];
if(it.childNodes.length && !useSelf){r=r.concat(getNodes(prop,val,meth,it,useSelf ));}
if( any ? it[prop] : (it[prop]!==undefined && (meth ? ""[meth] &&
String(it[prop])[meth](val) : it[prop]==val))){
r[r.length]=it;
}
}//nxt
return r;
};getNodes[null]=true; getNodes[undefined]=true;
getNodes("nodeType", 8) //all
getNodes("nodeType", 8, null, document.body) //body only
[/CODE]
[CODE]var els = document.body.getElementsByTagName( "*" );
for ( var i = 0, length = els.length; i < length; i++ ) {
if ( els[i].nodeName === "#comment" || els[i].nodeType === 8) {
val = els[i].nodeValue; // get the string
// do something
}
}
[/CODE]
@rnd_me , your script doe what exactly? Return the contents of the elements or a list of the nodes that I can harvest information from? Looks complicated.[/QUOTE]
[CODE]getNodes("nodeType", 8, null, document.body)[/CODE]
[CODE]<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>getComments</title>
<!-- ******** Get Comments Tool Utility ********* -->
<style type="text/css">
/* Basic style sheet comments here */
body {background:grey}
</style>
<script type="text/javascript">
/*------- In theory this script------------
------ should build a comments array -------
--------- out of the pages comments --------*/
alert
var comms = (function(){
// Define variables
// and regular expressions
var match, i;
var stripChars = /t/g;
// this one took bloody ages, and still needs work
var regScript = //{2}s?([sS]+?)(?=n)|/*s?([sS]+?)(?=*/)/g;
var regType = /SCRIPT|STYLE/
var comments = {};
// a few private methods
function _isComment(node){
if (node.nodeType === 8){
if (!comments[node.parentNode.nodeName]) { comments[node.parentNode.nodeName] = [];}
comments[node.parentNode.nodeName].push(node.data.replace(stripChars,""));
} else if (regType.test(node.nodeName)) { _scriptComs(node); }
return;
}
function _scriptComs(node){
if (!comments[node.nodeName]) { comments[node.nodeName] = [];}
while ((match = regScript.exec(node.innerHTML)) != null){
i = (match[1])? 1 : 2;
comments[node.nodeName].push(match[i].replace(stripChars," "));
}
}
return { // public methods here
get : function(node){
node = node.firstChild;
while (node){
this.get(node); _isComment(node); node = node.nextSibling;
}
return this;
},
output : function(){
var output = "";
for (props in comments){
output+=props+"n";
var i = comments[props].length, x = 0;
while (i--){ output+=comments[props][x++]+"n"; }
}
return output;
}
};
})();
window.onload = function(){alert(comms.get(document).output())}; // can change to document.body
</script>
</head>
<body>
<!--Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus a auctor sem. Quisque lorem urna, tempus sed iaculis vel, sodales a quam. In tincidunt enim est. Donec et ante sem, non mattis arcu. Proin luctus aliquet magna commodo aliquet. Integer ac velit tortor, in viverra erat. Praesent sem nisi, vulputate eu imperdiet vel, tempor sed lorem. Pellentesque eget libero in odio congue bibendum. Fusce tempor tellus at nunc tincidunt at consectetur sapien malesuada.-->
</body>
</html>[/CODE]
[CODE]HEAD
******** Get Comments Tool Utility *********
STYLE
Basic style sheet comments here
SCRIPT
------- In theory this script------------
------ should build a comments array -------
--------- out of the pages comments --------
Define variables
and regular expressions
this one took bloody ages, and still needs work
a few private methods
public methods here
can change to document.body
BODY
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus a auctor sem. Quisque lorem urna, tempus sed iaculis vel, sodales a quam. In tincidunt enim est. Donec et ante sem, non mattis arcu. Proin luctus aliquet magna commodo aliquet. Integer ac velit tortor, in viverra erat. Praesent sem nisi, vulputate eu imperdiet vel, tempor sed lorem. Pellentesque eget libero in odio congue bibendum. Fusce tempor tellus at nunc tincidunt at consectetur sapien malesuada.[/CODE]
[CODE]var comms = (function(){
var match, i;
var stripChars = /t/g;
var regScript = //{2}s?([sS]+?)(?=n)|/*s?([sS]+?)(?=*/)/g;
var regType = /SCRIPT|STYLE/
var comments = {};
function _isComment(node){
if (node.nodeType === 8){
if (!comments[node.parentNode.nodeName]) { comments[node.parentNode.nodeName] = [];}
comments[node.parentNode.nodeName].push(node.data.replace(stripChars,""));
} else if (regType.test(node.nodeName)) { _scriptComs(node); }
return;
}
function _scriptComs(node){
if (!comments[node.nodeName]) { comments[node.nodeName] = [];}
while ((match = regScript.exec(node.innerHTML)) != null){
i = (match[1])? 1 : 2;
comments[node.nodeName].push(match[i].replace(stripChars," "));
}
}
return {
get : function(node){
node = node.firstChild;
while (node){
this.get(node); _isComment(node); node = node.nextSibling;
}
return this;
},
output : function(){
var output = "";
for (props in comments){
output+=props+"n";
var i = comments[props].length, x = 0;
while (i--){ output+=comments[props][x++]+"n"; }
}
return output;
}
};
})();
window.onload = function(){alert(comms.get(document).output())};[/CODE]
the script itself is complicated, but using it shouldn't be.
[CODE]getNodes("nodeType", 8, null, document.body)[/CODE]
returns an array of all the comment nodes in body.
I believe that's exactly what you asked for...
if you want the text contents, the .data property of each element in the array contains the string version of the text inside each comment.[/QUOTE]
Yes thanks, I am just confused by it, I like to understand how it operates to appreciate what it does and it makes me wonder why functions do not already exist for this purpose...
SO... Is that <!-- HTML comments or does that include // --- and /* --- */ comment blocks as well? [/QUOTE]
[CODE]function getNodes(prop, needle, blnMatch, node){
var results=[], any=(needle==null);
node=node||document.documentElement;
if(node.splice){ node={childNodes:node}; }
for(var it, i=0, kids=node.childNodes;it=kids[i];i++){
if(it.childNodes.length){
results=results.concat(getNodes(prop, needle, blnMatch, it));
}
switch(true){
case any && it[prop]:
case it[prop]===needle:
case blnMatch && !!String(it[prop]).match(needle):
results[results.length]=it;
}
}
return results;
}//end getNodes()
function getNodes(prop, needle, blnMatch, node){
var results=[], any=(needle==null);
node=node||document.documentElement;
if(node.splice){ node={childNodes:node}; }
for(var it, i=0, kids=node.childNodes;it=kids[i];i++){
if(it.childNodes.length){
results=results.concat(getNodes(prop, needle, blnMatch, it));
}
switch(true){
case any && it[prop]:
case it[prop]===needle:
case blnMatch && !!String(it[prop]).match(needle):
results[results.length]=it;
}
}
return results;
}//end getNodes()
//usage example: get all comments from the body
getNodes("nodeType", 8, false, document.body) //body only[/CODE]
0.1.9 — BETA 6.17