/    Sign up×
Community /Pin to ProfileBookmark

Change CSS Classes

Hello,

I have a number of divs with the same id. I’d like to be able to change the CSS class of all these divs at once.

This is what I have so far:

[CODE]function highlightTask(taskName)
{
// unset all active highlights

// highlight the selected task
document.getElementById(taskName).className = “graphBarHighlight”;
}[/CODE]

This only works for one div. After the class has been changed for the first div nothing happens!

Any ideas? I was thinking about some sort of loop using a count of the ids?

Many Thanks,

dai.hop

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@ZnupiOct 15.2007 — Having more than one element with the same id is illegal (You will get validation errors). You will have to use names instead of ids (<div name="whatever">) and then, to loop through the divs with that name, you'll use this sequence:
<i>
</i>elements = document.getElementsByName(taskName);
for (var i=0; i &lt; elements.length; i++) elements[i].className = "graphBarHighlight";


Hope this helps ?
Copy linkTweet thisAlerts:
@dai_hopauthorOct 15.2007 — Fantastic! This is just the job ?

Any ideas why it won't work in IE though? Fine in Firefox.
Copy linkTweet thisAlerts:
@Declan1991Oct 15.2007 — Just after elements = line, add [code=php]alert(elements)[/code] and say what happens. I think it will return null if it is divs with the name, because for the only time IE is correct, and will not return divs. (Only A, APPLET, BUTTON, FORM, FRAME, IFRAME, IMG, INPUT, OBJECT, MAP, META, PARAM, TEXTAREA and SELECT are supported.) If you cannot rewrite the code use something like this:
[code=php]
document.IEgetElementsByName = function(name,tagname){
var elements = document.getElementsByTagName(tagname||"*");
var returnElements;
for (var i = 0; i < elements.length; i++) {
if (elements[i].name == name) {
returnElements[returnElements.length] = elements[i];
}
}
return returnElements.length>0?returnElements:false;
}
[/code]

It takes an optional tag name parametre which limits the results to those tags. Note that you only need to do that for the tags that are not defined in the specification.
×

Success!

Help @dai_hop spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.24,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...