John Montague
John Montague

Reputation: 95

How to use innerHTML in multiple locations?

I am trying to dynamically update text in more than one location. However I know the code below doesn't work because the same ID is used more than once. Any ideas?

<html>

Favorite things to eat<p id="fruit">Text will appear</p>
Things that grow on trees<p id="fruit">Text will appear</p>

Dinner<p id="fish">Text will appear</p>
Creature in the ocean<p id="fish">Text will appear</p>

</html>

The Javascript:

<script>

document.getElementById("fruit").innerHTML="Oranges";
document.getElementById("fish").innerHTML="Shark";

</script>

Upvotes: 0

Views: 5235

Answers (3)

Kokozaurus
Kokozaurus

Reputation: 639

The same effect would be achieved if you use class instead of id attribute and then with jquery select the elements with that class and set their text like so:

<html>
<body>
  <p class="fish"> some fish </p>
  <p class="fish"> other fish </p>
</body>
</html>

and then the javascript would be:

<script>
$(".fish").html("some text here");
</script>

ofcourse you need to add a link to jquery to the html page like so

<script type="text/javascript" src="http://jquery ..." />

Just find the right url. You can find it on jquery.com

Here's non jQuery way for those who don't like it:

Instead of the script above use:

<script>
var i, 
    elements = document.getElementsByClassName('fish');
for ( i = 0; i < elements.length; i += 1) {
  elements[i].innerHTML = "some text here";
}
</script>

This however might not work in some versions of IE.

Upvotes: 1

Paul S.
Paul S.

Reputation: 66324

You can make use of the native JavaScript document.querySelectorAll

Favorite things to eat <span class="fruit">Text will appear</span>
Things that grow on trees <span class="fruit">Text will appear</span>

Dinner <span class="fish">Text will appear</span>
Creature in the ocean <span class="fish">Text will appear</span>
function replaceTextInClass(className, text) {
    var elms = document.querySelectorAll('.' + className), i;
    for (i = 0; i < elms.length; ++i) {
        elms[i].textContent = text;
    }
}
replaceTextInClass('fruit', 'Oranges');
replaceTextInClass('fish', 'Shark');

DEMO

You could similarly use document.getElementsByClassName, the key thing to remember is you have to iterate over a NodeList similar to an Array.

Upvotes: 2

scartag
scartag

Reputation: 17680

You can't use the id multiple times.

You can however assign a class to the element and use jquery to get every element of that class.

<p class="fruit">text will appear</p>

The script.

<script type="text/javascript">

$(".fruit").html("Oranges");

</script>

Upvotes: 3

Related Questions