February 27, 2013

using document.getElementById

Question by Codejoy

I am having a heck of a time getting some data from a dom I want.

I have some html here:

 <ul id="userMenu">
      <li class="userGreet devi">I WANT THIS TEXT HERE </li><li> <a href="javascript:void(0)" class="more" title="Menu">Menu</a>
      <ul> ....
            <li class="home">   
            </li>
      </ul>
      ...</li>
 </ul>

I know if I say

var x = document.getElementById('userMenu');  

I can get “something” back (though this is all in a portal so its incredibly difficult to put java script break points into this). So I am not sure how I can go further to get the string "I WANT THIS TEXT HERE " ?

I think I have to walk through childNodes but not sure how or what exactly I am getting back so I can get at that string, also getElementById didn’t work for the class= would that be getElementByClass ?

New to this DOM stuff.

Answer by jfriend00

Using plain javascript and making your code more robust if the order of elements changes a little bit, you could use both the id and the class to get it like this:

var text = document.getElementById('userMenu').getElementsByClassName("userGreet")[0].innerHTML;

or using tag names, it could be done like this:

var text = document.getElementById('userMenu').getElementsByTagName("li")[0].innerHTML;

Answer by Starx

You can scan through like this

var x = document.getElementById('userMenu');  
var xChilds = x.childNodes;
var requiredElement = null;
for(var i = 0; i < xChilds.length; i++) {
   if(xChilds[i].className.indexOf('usergreet devi') !== -1) {
      requiredElement = xChilds[i];
      break;
   }
}

console.log(requireElement);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!