[Javascript] Walking the DOM
Paul Novitski
paul at juniperwebcraft.com
Sat Sep 9 00:25:57 CDT 2006
At 9/8/2006 12:17 PM, Terry Riegel wrote:
>If I have the following markup...
>
> <li class="anor" id="album01"><a href="album1.html">My Favorite
>Photos (58)</a></li>
>
>and... in my javascript I have...
>
> o=document.getElementById('album01');
>
>How do I reference (with the intent of changing) the content of the
>anchor? My goal is to replace the text
At 9/8/2006 12:49 PM, Peter Brunone wrote:
>Wouldn't that just be o.childNodes[0].innerHTML ?
At 9/8/2006 03:33 PM, Matt Warden wrote:
>var li = document.getElementById('album01');
>var anchor = li.firstChild;
>var textNode = anchor.firstChild;
Part of the question will always be: how stable is your markup? For
example, if you or anyone else ever changes the HTML by inserting a
carriage return between the LI tag and the A, then I believe the
firstChild and the first childNode of LI would be a text node (the
carriage return) and the anchor would be its next sibling. Perhaps
safer would be:
o=document.getElementById('album01');
var aAnchors = o.getElementsByTagName("A");
if (aAnchors.length != 1) return alert("Help! Kwazy
unexpected markup!");
Then your one and only expected anchor is aAnchors[0].
Again, if the contents of the anchor is a single text string then it
will indeed be the firstChild, but if anyone ever inserts a SPAN or
EM then you'll have two or more childNodes.
In the Gecko DOM Reference it suggests an iterative approach to
removing all the children of a parent:
// remove all children from element
var element = document.getElementById("top");
while (element.firstChild) {
element.removeChild(element.firstChild);
}
http://developer.mozilla.org/en/docs/DOM:element.removeChild#Example
With respect to innerHTML, the reference says: "Though not actually
a part of the W3C DOM specification, this property provides a simple
way to completely replace the contents of an element. ... As there is
no public specification for this property, implementations differ
widely. For example, when text is entered into a text input, IE will
change the value attribute of the input's innerHTML property but
Gecko browsers do not."
http://developer.mozilla.org/en/docs/DOM:element.innerHTML#Notes
I take that to mean that using removeChild is the safer course,
although you might get away with using innerHTML with few complaints.
Paul
More information about the Javascript
mailing list