Skip to content Skip to sidebar Skip to footer

Get The Text In A List Item And Modify It With Javascript

I have a bunch of HTML list items and what i want is to be able to read the text of a list item and then be able to give the user the ability to modify it. the structure of each li

Solution 1:

You need to get the textContent or innerText properties:

var li = document.getElementById(id);
var t = "textContent"in li.childNodes[0] ? "textContent" : "innerText";
alert(li.childNodes[0][t]);

innerText is implemented by IE and textContent is implemented by standards compliant browsers.

Alternatively, if you're certain that the element's first child will be a text node, you can use

alert(li.childNodes[0].childNodes[0].nodeValue);


Based on your comment below, we can make a safe assumption that white-space is interfering with the childNodes property in your example. This is normal - childNodes returns both elements and text nodes that are direct descendants of the given element. The alternative is to use children in newer browsers:
// 1st example using `children` insteadvar li = document.getElementById(id);
var t = "textContent"in li ? "textContent" : "innerText";
alert(li.children[0][t]);

// 2nd example using `children` insteadalert(li.children[0].childNodes[0].nodeValue);

children isn't supported pre Firefox 3.5 and in other older browsers. You could use li.getElementsByTagName("a") for the example that you've posted - but bear in mind that it will return all <a> element descendants, not just immediate children.

Solution 2:

What about this:

var li = document.getElementById(1);
var a = li.getElementsByTagName('a');

alert(a[0].innerHTML);

And before anyone can suggest to just use jQuery, here's the equivalent:

$('li#someid a').html();

In my opinion, if you're doing fine without jQuery, don't use it.

Post a Comment for "Get The Text In A List Item And Modify It With Javascript"