innerHTML strange behaviour

F

Francesca Baslen

Hello,

Please have a look a the code below. I have HTML (nested) list, each
item contains a hyperlink. I wish to select one particular item (here
#li1) and get the HTML fragment of the hyperlink (<a href="...">...</a>).
It sounds so easy, I really can't understand what's wrong with my code
and my use of innerHTML.

HTML fragment :

<ul id="toc">
<li id="li1">
<a href="page?1">Page 1</a>
<ul>
<li id="li2">
<a href="page?2">Page 2</a>
</li>
</ul>
</li>
<li id="li3"><a href="page?3">Page 3</a></li>
</ul>

Javascript :

var currentNode = document.getElementById("li1");
var myString = currentNode.getElementsByTagName("A")[0].innerHTML;
alert(myString);

I naturally expect myString to store the value:
<a href="page?id=1">Page 1</a>

But instead it stores: Page1, i.e. the text content of the node.

Thanks for your help!

F
 
D

David Dorward

var myString = currentNode.getElementsByTagName("A")[0].innerHTML;
alert(myString);

I naturally expect myString to store the value:
<a href="page?id=1">Page 1</a>

But instead it stores: Page1, i.e. the text content of the node.

The key word is "inner". The HTML inside the element. The element
isn't inside itself and isn't included.

Generally I suggest avoiding innerHTML entirely and sticking to DOM
methods instead.
 
F

Francesca Baslen

David Dorward was caught writing:
var myString = currentNode.getElementsByTagName("A")[0].innerHTML;
alert(myString);

I naturally expect myString to store the value:
<a href="page?id=1">Page 1</a>

But instead it stores: Page1, i.e. the text content of the node.

The key word is "inner". The HTML inside the element. The element
isn't inside itself and isn't included.

Generally I suggest avoiding innerHTML entirely and sticking to DOM
methods instead.
Ha, thanks David! You're right of course.
Stick to the DOM I will from now on.
I'll write some reusable code in order to parse the nodes, the
attributes, the inner content, and build the output string.

F.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,771
Messages
2,569,587
Members
45,099
Latest member
AmbrosePri
Top