Reputation: 3806
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.
Upvotes: 1
Views: 2984
Reputation: 4568
Try this...
document.getElementById('userMenu').children[0].innerHTML
Upvotes: 2
Reputation: 4853
Sorry if this is obvious, but... generally speaking, if you're going to be trying to access elements, give them IDs at the outset, it will save you lots of time.
<li id="ug0" class="userGreet devi">...</li>
Then of course
document.getElementById('ug0').innerHTML;
Upvotes: 0
Reputation: 707158
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;
Upvotes: 1
Reputation: 382092
You can use this :
var text = document.querySelectorAll('#userMenu li.userGreet.devi')[0].innerHTML;
See MDN's documentation of querySelectorAll.
Note that this won't work on IE7. To do this kind of thing more easily in a cross-browser fashion, you can use one of the popular DOM manipulation libraries like jQuery.
If your HTML is different from the text you want (i.e. you have markups for example), you might use this to get the interpreted text :
var element = document.querySelectorAll('#userMenu li.userGreet.devi')[0];
var text = element.innerText || element.textContent;
Note that here again libraries help you deal with those incompatibilities between browsers. Jquery would let you do
var text = $('#userMenu li.userGreet.devi').text();
Upvotes: 2
Reputation: 78941
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);
Upvotes: 1
Reputation: 2071
jQuery would make this easier. You could do something like
var text = $('#userMenu .userGreet.devi').text();
Upvotes: 0