Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 390
Dominic Avatar asked Apr 11 '12 07:04

Dominic


2 Answers

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>
like image 125
tusar Avatar answered Oct 13 '22 01:10

tusar


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.

like image 33
Vasyl Gutnyk Avatar answered Oct 13 '22 00:10

Vasyl Gutnyk