Simon
Simon

Reputation: 23141

getElementByClass().setAttribute doesn't work

why when i write

document.getElementByClass('home1').setAttribute('style', 'background-image:url(img/red_menu.PNG);');

it doesn't work? i have the element with class="home1"

with document.getElementById('home1')... works fine thanks

Upvotes: 8

Views: 34604

Answers (3)

Hai Nguyen Le
Hai Nguyen Le

Reputation: 111

Please use:

document.getElementsByClassName('home1')[0].setAttribute('style', 'background-image:url(img/red_menu.PNG);');

Upvotes: 0

Front-end Developer
Front-end Developer

Reputation: 410

If you have only one classname in your entire HTML file, then you could also use

  document.getElementsByClassName('navbar-nav')[0].setAttribute('id', 'navbar-toggle');

Upvotes: 6

T.J. Crowder
T.J. Crowder

Reputation: 1074295

It's getElementsByClassName, not getElementByClass; details here. Note that IE does not support this function (yet).

getElementsByClassName returns a NodeList of matching elements (rather than a single element), so:

var list, index;
list = document.getElementsByClassName("home1");
for (index = 0; index < list.length; ++index) {
    list[index].setAttribute(/* ... */);
}

For this sort of thing, you may want to use a library like jQuery, Prototype, Google Closure, etc., to pave over the various browser differences for you. They can save you a lot of time and trouble compared with dealing with those differences yourself.

For instance, in jQuery:

$(".home1").attr(/* ... */);

...applies that attribute (via jQuery#attr) to every element with the class "home1". Although in your particular case, you'd probably want jQuery#css instead.

Upvotes: 23

Related Questions