[thelist] Simple DOM Question

Matt Warden mwarden at gmail.com
Wed Oct 18 10:23:01 CDT 2006


On 10/18/06, Tim Palac <tymartist at hotmail.com> wrote:
> I have a question so simple you'll probably smack me for asking, but if I'm creating a link using DOM / Javascript how do I append text to the link?  I was trying to use appendChild but that was only adding text after the link, and not as the link text itself.  I even used the DOM Inspector and after doing that, the structure looked the same as in a page where the text was part of the link.  Thanks for your help!
>

The DOM is a tree, so you must append the text in the appropriate part
of the tree. Here you want text like this (simplified):

<p id="parent"><a>hello</a></p>

The tree version (without the id attribute) is:

p
|
+-a
  |
  +-"hello"

And I suspect you are ending up with:

p
|
+-a
|
+-"hello"

var p = document.getElementById('parent');
var a = document.createElement('a');
var txt = document.createTextNode('hello');
a.appendChild(txt);
p.appendChild(a);

Not:

p.appendChild(a);
p.appendChild(txt);

as I suspect you are doing currently.

that help?

-- 
Matt Warden
Cleveland, OH, USA
http://mattwarden.com


This email proudly and graciously contributes to entropy.



More information about the thelist mailing list