[Javascript] finding an element in the DOM sea
Paul Novitski
paul at novitskisoftware.com
Mon Jan 30 21:40:00 CST 2006
At 07:10 PM 1/30/2006, Jonathan Gold wrote:
>Thanks Paul, that is very helpful. But I am still uncertain _what_
>to call things on the page. Really, I just want to know how to
>address certain elements. I want the span elements in this case, to
>allow their background color to be changed to conform to the rest of
>the webpage. I can view the DOM of my page using the FF extension
>DOM Inspector. And I find that the node of my span element is named
>SPAN and that its parent element is called LI and its parent element
>is called UL, then BODY, then HTML, then something called #document.
>When I wanted to adjust the background color of the page as a whole,
>I simply wrote "document.bgColor = myColor". myColor was a variable
>that had already been set as a hex representation of a color. Now I
>want to set the background of the span elements to conform. I know
>this doesn't work, but just to show what it is I am trying to do,
>here's a line I tried: "document.html.body.ul.li.span.bgColor =
>myColor;" So my question is: how do I correctly address Mr. Span so
>that he will feel moved to respond to my requests? :~)
Hmm.
[I didn't know that document.bgColor was legal, but I guess it's
assuming you mean document.body.bgColor.] I figure you can get away
with document.body.bgColor because there's only one body tag in a
document, but it's an old-school method of referring to objects in
the DOM and I recommend you use getElementById() or
getElementsByTagName() instead. I wouldn't expect
document.html.body.ul.li.span.bgColor to work primarily because those
aren't unique elements in the document (which ul? which li? which span?).
[Rather than using the bgColor attribute, I would recommend using
style.backgroundColor so that it integrates more smoothly into your
use of stylesheets.]
Here are some ways of referring to a particular element:
- by unique tagName:
<body>
document.body.style.backgroundColor = "#FFF";
- by tagName array:
<form action=...>
document.forms[0].onsubmit = fnDoSomething;
(you can't refer to all tags as arrays)
- by id:
<span id="span123">
var oSpan = document.getElementById("span123");
oSpan.style.backgroundColor = "#FFF";
- by object in the DOM:
<span>
var aSpans = document.getElementsByTagName("SPAN");
aSpans[x].style.backgroundColor = "#FFF";
...where x = 0-N in the array of span elements in the document
So my earlier example of how to walk the DOM was precisely what you
want to do (whether you know it or not): generating an array of
objects you can cycle through to point to each individual span.
Clear as mud?
Paul
More information about the Javascript
mailing list