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!
You could use class, because id
s 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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With