March 18, 2013
Change ID attribute dynamically in for-loop
Question by Dymond
The title could be misleading but i will try to explain.
I have an Ajax function that gets the value of some XML nodes. Now I want to change the ID of every created element with value of the xml-nodes.
I have something like this.
XML file
<notes>
<note>
<text>Hello Dog</text>
<id>1</id>
</note>
<note>
<text>Hello Cat</text>
<id>1</id>
</note>
</notes>
Now for call every text node I use a loop
stickers = myXML.getElementsByTagName("note");
for( i = 0; i < stickers.length; i++) {
var idNod = (stickers[i].getElementsByTagName("id")[0].childNodes[0].nodeValue);
var textNod = (stickers[i].getElementsByTagName("text")[0].childNodes[0].nodeValue);
add_sticker(idNod);
add_sticker(textNod);
}
// add_sticker() is the function that created the elements dynamically …
So the output of this will become
Note1 = Hello Dog id 1,
Note2 = Hello Cat id 2
But I want somehow to use the idNod and use it as ID attribute
so it would look something like this
<div id=1>hello dog</div>
<div id=2>hello Cat</div>
In the loop I entered
stickers[i].setAttribute("id", idNod);
But that didn’t do anything, not neither gave me an error.
Answer by Starx
Why does your add_stickers
are called twice to create one element? You should design your function to take both values and create the element.
function add_sticker(idNod, textNod) {
var div = document.createElement("div");
div.id = idNod;
div.innerHtml = textNod;
//Other parts
};