How to access ul element's style via DOM2?

S

Spartanicus

How do I access the first ul's style via DOM2 from the following code?:

<body>
<div id="foo">
<ul>
<li><a href="#>foobar</a></li>
</ul>
<ul>
<li><a href="#>foobar</a></li>
</ul>
</div>
</body>

document.???.[0].style.display="block"
 
M

Michael Winter

How do I access the first ul's style via DOM2 from the following code?:

<body>
<div id="foo">
<ul>
<li><a href="#>foobar</a></li>
</ul>
<ul>
<li><a href="#>foobar</a></li>
</ul>
</div>
</body>

There are a couple of ways: using getElementsByTagName or walking the
document tree. Either way will start with:

if(document.getElementById) {
var foo = document.getElementById('foo');

/* Insert here... */
}

and use:

if(foo.getElementsByTagName) {
var lists = foo.getElementsByTagName('UL');
if(lists.length) {
var item = lists[0], style;
if((style = item.style)) {
style.<...> = ...;
}
}
}

or:

var item = foo.firstChild, style;
while(item && (1 != item.nodeType)) {item = item.nextSibling;}
if(item && (style = item.style)) {
style.<...> = ...;
}

Of course, this assumes that your document structure will be exactly as
indicated. I'm also being more defensive than I possibly need to be.

Hope that helps,
Mike


Code only reviewed, not tested.
 
D

DU

Spartanicus said:
How do I access the first ul's style via DOM2 from the following code?:

<body>
<div id="foo">
<ul>
<li><a href="#>foobar</a></li>
</ul>
<ul>
<li><a href="#>foobar</a></li>
</ul>
</div>
</body>

document.???.[0].style.display="block"

The easiest way would be

<ul>
<li id="idFirstLi"><a href="#">foobar</a></li>
</ul>

document.getElementById("idFirstLi").style.display = "block";

By the way, you're missing closing quotes on the href attribute values.

DU
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top