11

I want to replace the innerHTML of all divs with class "count" with: items1.innerHTML.

How can I do this?

lisovaccaro
  • 32,502
  • 98
  • 258
  • 410
  • 2
    You shouldn't do anything with innerHTML. http://stackoverflow.com/questions/7392930/why-should-y-innerhtml-x-innerhtml-be-avoided – Incognito Sep 13 '11 at 22:54

2 Answers2

20

Here you go:

var items = document.getElementById( 'items' ),
    divs = document.getElementsByClassName( 'count' );

[].slice.call( divs ).forEach(function ( div ) {
    div.innerHTML = items.innerHTML;
});

Live demo: http://jsfiddle.net/MGqGe/

I use this [].slice.call( divs ) to transform the NodeList into a regular array, so that I can call the forEach method on it.

Btw, careful with innerHTML. I personally would use a library (like jQuery) to clone the contents instead.

Community
  • 1
  • 1
Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • 3
    +1 for a straight JavaScript answer, but it should check for getElementsByClassName existence if used. – kinakuta Sep 13 '11 at 22:57
  • @kinakuta `getElementsByClassName` and `forEach` aren't implemented in IE8. If the OP requires a cross-browser solution, he should use a library. If support for IE8 is not required, use my code. – Šime Vidas Sep 13 '11 at 23:02
  • Use `querySelectorAll` and you'll gain IE8 support as long as you get rid of the `.slice` conversion to Array and the `forEach`. – user113716 Sep 13 '11 at 23:49
  • 1
    @patrick If support for IE8 were required (hypothetically speaking), one could have a `ie8.js` file (pushed to IE8 via conditional comments) which would contain manual implementations of `getElementsByClassName`, `forEach`, etc. just for IE8. That way those methods could still be used (despite IE8). As for the slice hack, it would probably be more reasonable to have a `toArray` utility function for that anyway (which would then do it the "slow way" by manually copying the references of all indexes). – Šime Vidas Sep 14 '11 at 00:40
12

you can do this by jQuery this way

$("div.count").html("new content");
MhdSyrwan
  • 1,613
  • 3
  • 19
  • 26
  • 5
    A more efficient selector is $('div.count') - as it relies on the fast DOM operation 'getElementsByTagName' to only fetch divs as a starting point. – Ben Hull Sep 13 '11 at 22:52
  • 1
    @Beejamin And it does what the OP asked ("all divs with class 'count'"). Instead of possibly selecting extra elements. – Paul Sep 13 '11 at 22:56