Click to See Complete Forum and Search --> : How do you apply an attribute to all childNodes, and their sub-nodes?


hotwheelharry
June 10th, 2008, 06:33 AM
I wanted to know how to make a script that would take a xml element (ie. <div>) and then apply an attribute to it, it's childNodes, and then to it's childNodes' nodes, and so on. Basically to all sub-children of the element.

I made a script but it somehow gets lost in an infinite loop.

If someone could help me out, that would be fantastic!

Here is my script but it's broken, maybe you could fix it or write a simple new one, either would help me out.


//in FF, and maybe others, it returns "\n" & " " as elements...
//so this just checks to see if the tagName property is there,
//thus meaning it has to be a real element (ex: <div>)
//then it returns all the ones it finds as real in a new array
function GetRealChildren(htmlObject){
var realChildElements = new Array();

for(k = 0; k < htmlObject.childNodes.length; ++k){
if(htmlObject.childNodes[k].tagName){
realChildElements.push(htmlObject.childNodes[k]);
}
}
//alert(htmlObject.id + " has " + realChildElements.length + " children");
return(realChildElements);
}

//this is supposed to actually (recursively) add the attributes
//to the elements and it's sub-nodes
function GiveAllRealChildrenAttribute(htmlObj){
var count = 0;
var realChildren = GetRealChildren(htmlObj); //sortof like object.childNodes

//probably only executed (the next 2 lines) if it is the first iteration of recursion
if( htmlObj.getAttribute("theAttributeName) == null){
htmlObj.setAttribute("theAttributeName", "theAttributeValue");
}
else{
//do nothing, just give it to kids then
}

//only gives it to kids
for(j = 0; j < realChildren.length; j++){
//if it has babies, give it the attribute, then all it's babies,
//and it's babies' babies the attribute (recursion)
if(GetRealChildren( realChildren[j] ).length > 0){
realChildren[j].setAttribute("theAttributeName", "theAttributeValue");
count += GiveAllRealChildrenAttribute( realChildren[j] );
}
else{ //if it has no babies, just give it attribute
realChildren[j].setAttribute("theAttributeName", "theAttributeValue");
count += 1;
}
}
return(count);
}

GiveAllRealChildrenAttribute( document.getElementById("the_Element_To_Appy_Attributes_To") );


Comments should explain the basic idea.

PeejAvery
June 10th, 2008, 09:08 AM
Why don't you just do a traditional DOM walk?

function walkDOM(obj, f) {
f(obj);
node = node.firstChild;
while (obj) {
walkDOM(obj, f);
node = node.nextSibling;
}
}

function doSomething(obj) {
// obj should be your node...style it as you please
}

// call the walk function
walkDOM(document.getElementById('PARENT_ID'), doSomething);