Johan
Johan

Reputation: 19072

Update two same value in html with one ajax response

I have two <span> -tags with the same ID in different places om my page. I know it's wrong to use the same ID twice. It's no problem for me to change the ID's to classes.

HTML:

<span id="tumme">4</span>
...
<span id="tumme">4</span>
....

is updated by

AJAX:
document.getElementById(tumme).innerHTML = xmlHttp.responseText;

but only on the <span> is updated.

Any ideas?

Upvotes: 0

Views: 1004

Answers (5)

T0xicCode
T0xicCode

Reputation: 4941

Use getElementsByClass:

function getElementsByClass(searchClass,node,tag) { var classElements = new Array(); if ( node == null ) node = document; if ( tag == null ) tag = '*'; var els = node.getElementsByTagName(tag); var elsLen = els.length; var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"); for (i = 0, j = 0; i < elsLen; i++) { if ( pattern.test(els[i].className) ) { classElements[j] = els[i]; j++; } } return classElements; }

Upvotes: 0

Quentin
Quentin

Reputation: 943561

Since an id must be unique per document, you cannot have two elements with the same id. Find some other way to identify the elements. A class is the standard means to mark an element as a member of a group. You could also give them different ids and then store those ids in an array.

<span class="tumme"> 4 </span>

Then when you get the data from your XHR request back, find all the elements and loop over them. While you can roll your own method for getting elements by class name, it is easier to use an existing one.

Looping over them will be just a case of:

for (var i = 0; i < elements.length; i++) {
    elements[i].innerHTML = xmlHttp.responseText;
}

Upvotes: 2

jhurshman
jhurshman

Reputation: 6067

Well, you could use the NAME attribute. It is perfectly valid to have multiple nodes with the same NAME.

So you would have these nodes:

<span id="somethingUnique1" name="tumme"></span>
<span id="somethingUnique2" name="tumme"></span>

To update them, you would do something like:

var nodes = document.getElementsByName("tumme");
for (var i = 0, node; node = nodes[i]; i++) {
  node.innerHTML = xmlHttp.responseText;
}

Upvotes: -3

Dave Archer
Dave Archer

Reputation: 3060

Change the id= to class= because 2 elements with the same id is WRONG

Then either using jQuery and its powerful selectors, or here's a function some guy wrote to get all elements by class name

Upvotes: 2

Mythica
Mythica

Reputation: 1122

From the W3C website about id's (http://www.w3.org/TR/REC-html40/struct/global.html#h-7.5.2):

This attribute assigns a name to an element. This name must be unique in a document.

In other words, give the second span another id to fix it.

Upvotes: 2

Related Questions