Javascript 用相同的类替换所有 div 的innerHTML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7409478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:10:07  来源:igfitidea点击:

Replace innerHTML of all divs with same class

javascript

提问by lisovaccaro

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

我想用“count”类替换所有div的innerHTML:items1.innerHTML。

How can I do this?

我怎样才能做到这一点?

回答by ?ime Vidas

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/

现场演示:http : //jsfiddle.net/MGqGe/

I use this [].slice.call( divs )to transform the NodeListinto a regular array, so that I can call the forEachmethod on it.

我使用它[].slice.call( divs )来将NodeList转换为常规数组,以便我可以调用forEach它的方法。

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

顺便说一句,小心 innerHTML。我个人会使用一个库(如 jQuery)来克隆内容。

回答by MhdSyrwan

you can do this by jQuery this way

你可以通过 jQuery 这种方式做到这一点

$("div.count").html("new content");