Dominic
Dominic

Reputation: 235

document.getElementById.innerHTML works only once - how to configure global copy elements?

I want to create an external js-file, in which I can configure the copy of several elements in my html file. I'm using document.getElementById("id").innerHTML = "what ever"; to "inject" or "add" my copy to html elements that have a certain id.

This works out fine, however when I have more than one element with the same id in my html file, the html from my js-file is only added to the first element but the html from my js-file should be added to all elements with the same id

That's my html construct:

<html>
<head>
<script src="copy.js" type="text/javascript" charset="utf-8"></script>
<script src="jquery.js" type="text/javascript" charset="utf-8"></script>
</head>

<body>

<div>
<strong id="back-button"></strong>
</div>

....

<div>
<strong id="back-button"></strong>
</div>

</body>
</html>

And that's my JS file:

$(function() {
    $(document).ready(function addcopy() {

        /* global */
        document.getElementById("back-button").innerHTML = "go back";
});
});

Any help or tip is much appreciated. Thanks!

Upvotes: 6

Views: 14326

Answers (5)

Vasyl Gutnyk
Vasyl Gutnyk

Reputation: 5039

In js you can do it like this:

 document.getElementsByClassName('message')[0].innerHTML = "Good afternoon:)!";

Then you can loop through all elements of this class.

Upvotes: 1

Shiv Shankar
Shiv Shankar

Reputation: 76

Please use class instead of id for the HTML elements and use jquery to fill in the required text.

<div>
<strong class="back-button"></strong>
</div>


$('.back-button').text('go back');   // OR
$('.back-button').html('go back');

Upvotes: 0

tusar
tusar

Reputation: 3424

You could use class, because ids can be used only once.

<html>
<head>
<script src="copy.js" type="text/javascript" charset="utf-8"></script>
<script src="jquery.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div class="back-button">
</div>
....
<div class="back-button">
</div>
</body>
</html>

And in javascript :

<script type="text/javascript">
     $(document).ready(function addcopy() {
         /* global */
         $(".back-button").html("<strong>go back</strong>");
     });
</script>

Upvotes: 6

ThiefMaster
ThiefMaster

Reputation: 318478

You have jQuery, why not use $('#back-button').html('go back') instead of the plain/native JS?

However, you have more than one button and IDs must be unique, so you cannot use an id for this. Use class="back-button" and the following jQuery code:

$('.back-button').html('go back');

Upvotes: 0

Michael Laffargue
Michael Laffargue

Reputation: 10294

id attribute should be unique, I know that in JQuery if you want to use multiple selector you can use class instead.

Or you can use name and the getElementsByName() function that will give you an array of elements in Javascript.

Upvotes: 0

Related Questions