Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace innerHTML of all divs with same class

Tags:

javascript

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

How can I do this?

like image 946
lisovaccaro Avatar asked Sep 13 '11 22:09

lisovaccaro


People also ask

What method is used to replace the innerHTML of an element?

Answer: Use the jQuery html() Method You can simply use the jQuery html() method to replace innerHTML of a div or any other element.

Why you shouldn't use innerHTML?

'innerHTML' Presents a Security Risk The use of innerHTML creates a potential security risk for your website. Malicious users can use cross-site scripting (XSS) to add malicious client-side scripts that steal private user information stored in session cookies.

How use innerHTML with div tag?

Using the innerHTML attribute: To append using the innerHTML attribute, first select the element (div) where you want to append the code. Then, add the code enclosed as strings using the += operator on innerHTML.


2 Answers

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.

like image 166
Šime Vidas Avatar answered Oct 16 '22 19:10

Šime Vidas


you can do this by jQuery this way

$("div.count").html("new content");
like image 45
MhdSyrwan Avatar answered Oct 16 '22 19:10

MhdSyrwan