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 list item is the same:
<li id='1' class='attachment'>
<a href='link.html'>TEXT VALUE I WANT TO READ AND MODIFY</a>
<a href='link2.html'><img src'img1.jpg'></a>
<a href='link3.html'><img src'img2.jpg'></a>
</li>
at the moment i am able to get the list item using
li = document.getElementById(id);
but if i get it to print out something like
li.childNodes[?]
li.childNodes[?].data
li.childNodes[?].nodeValue etc...
i am never able to get it to print "TEXT VALUE I WANT TO READ AND MODIFY", it always gives null, undefined or [object Text] or something similar. any help would be greatly appreciated.
You need to get the textContent or innerText properties:
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
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:
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.
What about this:
And before anyone can suggest to just use jQuery, here's the equivalent:
In my opinion, if you're doing fine without jQuery, don't use it.