On May 28, 5:20 pm, Gregor Kofler <use...@gregorkofler.atwrote:
SM meinte:
Hello, i need to add a classname to an element <ausing JavaScript.
I've tried a couple of thing with no success.
This is an small piece of my code:
...
<li><a href="<?php echo $cd_img; ?>" onClick="show_picture(this);
return false;">image 1</a></li>
<li><a href="<?php echo $cd_img; ?>" onClick="show_picture(this);
return false;">image 2</a></li>
...
<img id="cover" src="<?php echo $cd_cover; ?>" alt="" /></div>
function show_picture(picture) {
var source = picture.getAttribute("href");
var cover = document.getElementById("cover");
cover.setAttribute("src", source);
//??????doesnt work
var el_a = document.getElementById("a");
el_a.className = "here";
}
As expected. Use other methods to get element references, like
getElementsByTagName() (returns a collection of elements with a given
name), or give your element a name or id and access it with
getElementById() or getElementsByName().
Gregor
--http://photo.gregorkofler.at::: Landschafts- und Reisefotografiehttp://web.gregorkofler.com ::: meine JS-Spielwiesehttp://www.image2d.com ::: Bildagentur für den alpinen Raum
getElementByTagName doesn't work for me. getElementById does work ok.
I can't imagine having 30+ <aand give an 'id' tag for each. That's
just BAD programing in my opinion.
That's why i was looking for a general rule. Since i'm passing 'this'
in the function as a parameter, i was wondering if i could get the
parent or something similar and then add a class name. But then again,
i will need a way to undo that classname when i select another <a>.
I did more research and came up with this:
<ul id="nav_cd_imgs">
...
<li><a href="<?php echo $cd_img; ?>" onClick="show_picture(this);
return false;">image 1</a></li>
<li><a href="<?php echo $cd_img; ?>" onClick="show_picture(this);
return false;">image 2</a></li>
...
</ul>
var els_a =
document.getElementById("nav_cd_imgs").getElements ByTagName("a").length;
//testing purposes
alert(els_a);
//switch off all className in all <a>
for (i=0; i<els_a; i++) {
?????
}
//switch on the <aselected with a className
????
I just need to find how to get the <aselected. Any hints, meanwhile,
i'll continue searching the web and post the answer here if i find
something.
Thanks
Marco