Mr. Garrison
Mr. Garrison

Reputation: 33

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="myDiv"></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?

Upvotes: 0

Views: 100

Answers (3)

BoltClock
BoltClock

Reputation: 724452

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');

Upvotes: 1

letronje
letronje

Reputation: 9148

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");

Upvotes: 0

Jason
Jason

Reputation: 1183

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

Upvotes: 7

Related Questions