Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
Home
Discussion GroupsGeneralPHPASPPerlColdFusionFlashHTML, CSS, ScriptsBrowsers

Webmaster Forum / HTML, CSS, Scripts / JavaScript / August 2007



Tip: Looking for answers? Try searching our database.

innerHTML strange behaviour

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Francesca Baslen - 31 Aug 2007 11:45 GMT
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
David Dorward - 31 Aug 2007 12:26 GMT
On Aug 31, 11:45 am, Francesca Baslen <francesca.bas...@gmail.com>
wrote:

> var myString = currentNode.getElementsByTagName("A")[0].innerHTML;
> alert(myString);
[quoted text clipped - 3 lines]
>
> 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.

--
David Dorward
http://dorward.me.uk/
http://blog.dorward.me.uk/
Francesca Baslen - 31 Aug 2007 12:56 GMT
David Dorward was caught writing:
> On Aug 31, 11:45 am, Francesca Baslen <francesca.bas...@gmail.com>
> wrote:
[quoted text clipped - 17 lines]
> http://dorward.me.uk/
> http://blog.dorward.me.uk/

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.
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.