7

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

Simon
  • 22,637
  • 36
  • 92
  • 121
  • Re your edit, you must have been doing that while I was editing my answer to warn you that it returns a NodeList, not an element (since it can match multiple elements!). If you read the linked documentation you'll have a better idea what it does. Also, again, if you're using IE, it's not going to work, full stop. – T.J. Crowder Apr 02 '10 at 09:31
  • @T.J. Crowder ok, thanks. i'll read it, but can you now say me why it can't setattribue of all NodeList? – Simon Apr 02 '10 at 09:33
  • Because the DOM doesn't define that sort of meta-operation (allowing you to call a function on a list and applying that to every element of the list). I think you'll like jQuery, it does that sort of meta-operation. Worth taking a look. – T.J. Crowder Apr 02 '10 at 09:36
  • You also should not use `setAttribute` on HTML documents: it fails for many attributes in IE6-7, including style. Use the DOM Level 2 HTML/CSS properties directly, it is more readable as well as more reliable. `element.style.backgroundImage= 'url(img/red_menu.PNG)';` – bobince Apr 02 '10 at 10:58

3 Answers3

22

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
6

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');
Front-end Developer
  • 400
  • 1
  • 6
  • 17
0

Please use:

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

Hai Nguyen Le
  • 111
  • 1
  • 2