[Javascript] finding an element in the DOM sea
Paul Novitski
paul at novitskisoftware.com
Mon Jan 30 19:23:41 CST 2006
At 04:41 PM 1/30/2006, Jonathan Gold wrote:
>I have some text that is inside a <p><ul><li><span class="">
>situation. My page is about how to change colors on the web. When I
>change the background color for the whole page, these elements that
>are inside of lists and span classes ... their background doesn't
>change. So I want to talk to them. So that I don't have to bother
>the list each time, my question is: In general, and specifically,
>how do I determine the (as-it-were) 'address' of each element on my
>page so I can direct javascript commands to it? Here's the page:
>http://home.pacbell.net/jonnygee/auxiliary/colorpage.htm Try any
>change in color and you will see my problem.
You can walk the DOM this way:
__________________________
HTML:
<ul id="instructions">
<li> ... <span class="xxx"> ...
__________________________
JavaScript:
// bail if the browser doesn't support the DOM
if (!document.getElementById) return;
if (!document.getElementsByTagName) return;
// point to the list
var oUL = document.getElementById("instructions");
// get an array of the SPAN elements within the list
var aSpans = oUL.getElementsByTagName("span");
// walk the list
for (var iSpan = 0; iSpan < aSpans.length; iSpan++)
{
// if this span fits your criteria...
if (aSpans[iSpan].className && aSpans[iSpan].className == "xxx")
{
do something...
}
}
__________________________
If you've got a whole whack of spans, only a few of which are ones
you're interested in, you can add the relevant spans you find to an
array. Each element of the array will point to an actual span, so
you can cycle through the array to examine & modify their classNames,
adjust their styling, etc., to your heart's content.
The if-test I used above:
if (aSpans[iSpan].className && aSpans[iSpan].className == "xxx")
means, "if the span has a className and if the className is X" to an
prevent error if a span doesn't have class at all. As I recall, this
extra test isn't necessary if you're using regular expressions to
test the value of the class name.
Paul
More information about the Javascript
mailing list