0

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

Vicky
  • 16,679
  • 54
  • 139
  • 232
  • Are you aware that `document.getElementById('mainDiv').firstChild;` is likely a text node? `document.getElementById('mainDiv').childNodes;` would work better. –  Nov 25 '11 at 17:22

4 Answers4

2

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...

document.getElementById('subDivClass').getElementsByTagName('h2').firstChild.nodeValue

.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 nodeValue though 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...

 for (i in document.getElementById('mainDiv')) {alert('i = '+i);}

It should be noted that if you're stuck using the HTML parser .nodeName will be all uppercase (e.g. the old Internet Explorer way) versus using the XML parser (application/xhtml+xml) the .nodeName will 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 previousSibling and nextSibling that line breaks alone will create a textNode and those line breaks will mess with CSS (setting the font-size to 5px will generally eliminate this).

John
  • 1
  • 13
  • 98
  • 177
  • Thanks for your reply.. but I don't know how can I write the for loop I want using document.getElementById('subDivClass').getElementsByTagName('h2').firstChild.nodeValue because getElementsByTagName will in itself be a list... What if I have to do things on each element of this list ? – Vicky Nov 28 '11 at 08:59
  • Try... alert(document.getElementById('mainDiv').getElementsByTagName('div')[0].childNodes[0].nodeName); ...if that works then replace ('div')[0] with('div')[i] and stick it in to the loop. – John Nov 28 '11 at 09:10
  • alert(document.getElementById('myTab').getElementsByTagName('div')[0].childNodes[0].nodeName); gives H2. How to fetch the value in it ? Because my logic depends on the value I have in H2 i.e. apple, orange, banana, etc. alert(document.getElementById('myTab').getElementsByTagName('div')[0].childNodes[0].nodeValue) gives null – Vicky Nov 28 '11 at 09:15
  • alert(document.getElementById('myTab').getElementsByTagName('H2')[i].childNodes[0].nodeValue); -- This works.. Is this approach fine ??? – Vicky Nov 28 '11 at 09:19
  • That's using the standard DOM methods, NOT innerHTML. You'll find getElementsByTagName, childNodes and nodeValue are part of the official DOM specification and are wholley reliable all the way back to IE 5.5, Opera 7, etc. Note that IE 5.0 has a huge bug with getElementsByTagName. I don't bother with IE6 and older at this point though however these methods are DOM level 2 I think (if not DOM level 1) and they've been around for a very long time. – John Nov 28 '11 at 09:23
  • Yes, confirmed, they are part of DOM level 1, it doesn't get any more reliable than that! http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html – John Nov 28 '11 at 09:24
  • thanks a lot for your reply!! I have one more doubt where in I am unable to pick up the icon image to be displayed... I have placed the question today under image, javascript tag.. Could you look at that as well please!! – Vicky Nov 28 '11 at 09:27
0

If you want all the H2 elements inside the mainDivClass you can use the getElementsByTagName method:

var outerDiv = document.getElementById("mainDiv");
var h2s = outerDiv.getElementsByTagName("h2");

This returns all the H2 elements as an array of elements.

Alejandro Martin
  • 5,691
  • 1
  • 17
  • 21
  • thanks for the answer. I have updated the question. Can you pls tell how my requirement could be met through your answer!! – Vicky Nov 25 '11 at 11:02
0
var answer = function () {
    var parent = document.getElementById("mainDiv"),
        h2 = parent.getElementsByTagName("h2"),
        a = h2.length,
        b;
    for (b = 0; b < a; b += 1) {
        switch (h2[b].innerHTML) {
        case "one":
            //do something
            break;
        case "two":
            //do something
            break;
        default:
            //do something else
            break; 
        }
    }
};
austincheney
  • 1,097
  • 7
  • 8
  • thanks for the answer. I have updated the question. Can you pls tell how my requirement could be met through your answer!! – Vicky Nov 25 '11 at 11:03
0

The h2 value will be used as below:

 for (var i = 0; i < tabLists.length; i++) { 
      var anchor = tabLists[i].firstChild; 
      var iconFile;


      if(tabLists[i].firstChild.innerHTML == "Tab 0")
      {
        iconFile = 'one.png';                     
      }

      else if(tabLists[i].firstChild.innerHTML == "apple")
      {
        iconFile = 'apple.png';
       }

      else if(tabLists[i].firstChild.innerHTML == "orange")
             {
                iconFile = 'banana.png';
       }

      else if(tabLists[i].firstChild.innerHTML == "banana")
             {
                iconFile = 'orange.png';
       }

      anchor.style.backgroundImage = 'url(' + iconFile + ')'; 
      anchor.style.backgroundRepeat = 'no-repeat';        
      anchor.style.backgroundPosition = '1px 2px';        
      anchor.className = 'toplevel-tab';

    } 
Vicky
  • 16,679
  • 54
  • 139
  • 232