I have a div with id, which has some other div’s without id.
Some thing like:
<div class="mainDivClass" id="mainDiv">
<div class="subDivClass">
<h2>one</h2>
Hello One!!
</div>
<div class="subDivClass">
<h2>two</h2>
Hello Two!!
</div>
<div class="subDivClass">
<h2>three</h2>
Hello Three!!
</div>
</div>
In my javascript, I am looping through above div like:
var divLists = document.getElementById('mainDiv').firstChild.childNodes;
for (var i = 0; i < tabLists.length; i++) {
var anchor = divLists[i].firstChild;
var iconFile;
if(i==0)
{
iconFile = 'details.png';
}
else
{
iconFile = 'search1.png';
}
anchor.style.backgroundImage = 'url(' + iconFile + ')';
anchor.style.backgroundRepeat = 'no-repeat';
anchor.style.backgroundPosition = '1px 2px';
anchor.className = 'toplevel-tab';
}
As shown, I am setting iconFile variable on value of i. So for i = 0, it would be details.png while for all others, it would be search1.png.
Now, I want to decide the iconFile variable value based on the h2 value of the element.
That is, if h2 is banana, banana.png will go in iconFile but if h2 is orange, orange.png will be selected.
How to get h2 value inside javascript ?
Thanks for reading!!
Nik
Don’t use innerHTML, it’s an unreliable proprietary Microsoft method; should you get used to using it you will immediately begin having problems if you start coding at an application level and not be able to figure out why. Stick to using DOM specifications instead.
An example that you can obviously throw in to a loop…
.parentNode – The parent element of the currently referenced element.
.parentNode.parentNode.parentNode – You can use this as much as you want to go up or around the DOM.
.childNodes[0] – Index of child elements, does NOT contain reference to text nodes AFTER an element (use treewalker for that).
.nodeValue – The text value of a node, do NOT use innerHTML.
.textContent – Gets or sets the text of an element (but no child elements); a bit easier than
nodeValuethough it still has reasonable limitations..previousSibling – The element BEFORE the reference element, not a child/parent.
.nextSibling – The element AFTER the reference element, not a child/parent.
You can reveal all objects (e.g. methods, properties and other objects) for any object using the in operator to discover what else is available to you…
It should be noted that if you’re stuck using the HTML parser
.nodeNamewill be all uppercase (e.g. the old Internet Explorer way) versus using the XML parser (application/xhtml+xml) the.nodeNamewill properly return the element’s name as lowercase (unless you’re really in to the 90’s style or something).It should also be noted that when you use
previousSiblingandnextSiblingthat line breaks alone will create atextNodeand those line breaks will mess with CSS (setting thefont-sizeto 5px will generally eliminate this).