Evertjan. wrote in message news:
[email protected]...
wrote on 10 okt 2005 in comp.lang.javascript:
I have a list (i..e <UL> <LI>) where each <LI> contains a <DIV> and
text in it. [...]
Using javascript how do I read the content of each item in the list.
Many ways, here an example:
<UL id=ulx>
<LI>
<DIV> text here 1</DIV>
</LI>
<LI>
<DIV> text here 2</DIV>
</LI>
<LI>
<DIV> text here 3</DIV>
</LI>
</UL>
<script type='text/javascript'>
var ulx = document.getElementById('ulx')
f = ulx.firstChild
t = f.innerHTML
alert(t)
t = f.firstChild.innerHTML
alert(t)
f = f.nextSibling
t = f.innerHTML
alert(t)
t = f.firstChild.innerHTML
alert(t)
f = f.nextSibling
t = f.innerHTML
alert(t)
t = f.firstChild.innerHTML
alert(t)
</script>
different browsers tend to react differently to white spaces between tags
<ul>
<li>
<div>text</div>
</li>
</ul>
in Firefox for instance, will end up as
--+-- <ul> ELEMENT_NODE
| +-- TEXT_NODE
| +-+-- <li> ELEMENT_NODE
| | +-- TEXT_NODE
| | +-+-- <div>- ELEMENT_NODE
| | | --- "text" TEXT_NODE
| | --- TEXT_NODE
| --- TEXT_NODE
--- TEXT_NODE
Why do I mention this?
because you need to find the nodes that get to the text you want.
Evertjan showed you a simple way to access the text.
although if you don't write
<ul><li><div>text 1</div></li><li><div>text 2</div></li></ul>
you're going to end up with errors in Firefox.
you can access the UL or if you have more than one UL
with getElementsByTagName()
I modified Evertjan's script a bit to /loop/ through all ULs
and the LIs.
What I did not do is loop through nested lists.
(other than that they would just add up to the number of ULs)
I'm afraid there are other issues which hopefully will be pointed out
by someone who knows more about nuances and pitfalls of JavaScript
<script type="text/javascript">
var uls = document.getElementsByTagName("ul");
alert("how many ULs? " + uls.length);
var ulx, l, c, t;
for (var ulxs=0; ulxs<uls.length; ulxs++){
ulx = uls[ulxs];
for (var lis=0; lis<ulx.childNodes.length; lis++){
l=ulx.childNodes[lis];
if (l.nodeType==1) {
c=l.innerHTML;
if (!!l.textContent) t=l.textContent;
else if (!!l.firstChild.innerHTML) t=l.firstChild.innerHTML;
alert("the content is:\n" + c + "\nor as text\n" + t)
}
}
}
</script>
The above script would probably be better if implemented as a function()
and then called when needed.