views:

58

answers:

4
    <ul class="leftbutton" >
            <li id="menu-selected">Sample 1</li>
            <li>Sample 2</li>
            <li>Sample 3</li>
            <li>Sample 4</li>
            <li>Sample 5</li>
    </ul>

I want to get the text of the li item which the id="menu-selected".
Right now I am doing something like

   document.getElementById('menu_selected').childNodes.item(0).nodeValue

Is there any simpler way of doing the same?

+2  A: 

In your case:

document.getElementById('menu_selected').innerHTML
Alsciende
+1 beat me to it
David Hedlund
A: 

Try document.getElementById('menu_selected').text

Crimson
It should be `textContent` in FF and `text` in IE
Amarghosh
@Amarghosh: It's `innerText` in IE, `text` only applies to a few elements.
Andy E
+3  A: 

If you have HTML inside the LI elements and you only want to get the text, you need innerText or textContent.

var liEl = document.getElementById('menu_selected');
var txt = liEl["innerText" in liEl ? "innerText" : "textContent"];

To avoid using this conditional statement every time, you could just declare a global variable:

var textContentProp = "innerText" in document.body ? "innerText" : "textContent";
function getText()
{
    return document.getElementById('menu_selected')[textContentProp];
}
Andy E
A: 

If you can use jQuery it boils down to

var text = $('#menu_selected').text();
korchev