开发者

Why is this small javascript not working?

I have multiple instances of a div with an id of "myDiv" on a page. I want to replace the contents of these divs. When I use this javascript:

function replaceContent(id, content) {
    var container = document.getElementById(id);
    container.innerHTML = content;
}

replaceContent('myDiv', 'hello there');


<div id="myDiv"></div>
<div id="myDi开发者_运维技巧v"></div>
<div id="myDiv"></div>

It only replaces the content inside one of those divs and not all of them. If I use the .html() function of jquery instead, it replaces the contents of all divs. Is there any way I can get the above js to work in the same way?


id values must be unique - you can't have more than one id with the same name and update all of them.


I have multiple instances of a div with an id of "myDiv" on a page.

This is where you're doing it wrong. You cannot assign an ID to multiple elements on a page - it has to be unique.

It only replaces the content inside one of those divs and not all of them.

This happens because getElementById() returns only the first-matched element in case multiple such elements are matched.


To solve this, assign a class instead of an ID to the divs you want to target, and if you can use jQuery, use this instead (assuming class="myDiv"):

function replaceContent(className, content) {
    $('div.' + className).html(content);
}

// This appends className so the selector becomes $('div.myDiv')
replaceContent('myDiv', 'hello there');


IDs have to be unique. You can use the same class name for all divs and then use a css selector.

<div id="div1" class="mydivs">blah</div>
<div id="div2" class="mydivs">blah123</div>

For e.g. In JQuery, you could do:

$('.mydivs').html("whatever");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜