0

I'm able to change the CSS ID of an item with Javascript through a simple code like this:

<div id="teststyle1">Test Text, 1-1</div>

<button type="button" onclick="document.getElementById('teststyle1').style.color='red'"> Test 1 </button>

However, when I try to add in a second line of text (like in the full example below) with the same ID, only one of them gets changed. Is there a simple fix to this issue where both of the items would be changed?

Example:

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#teststyle1{
text-decoration: underline;
}
</style>
</head>
<body>

<div id="teststyle1">Test Text, 1-1</div>
<div id="teststyle1">Test Text, 1-2</div>

<button type="button" onclick="document.getElementById('teststyle1').style.color='red'">Test 1</button>

</body>
</html>

Any help is greatly appreciated!

  • 1
    IDs should be unique, maybe go for a approach with using class names? https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName - works from IE9+ – hank Nov 03 '13 at 08:56
  • Actually, instead of changing styles inline, set another class name, it's much cleaner to have all styles in one place – hank Nov 03 '13 at 08:57
  • 4
    Not should, **must** be unique. – Barmar Nov 03 '13 at 08:57
  • This is really basic. Before starting JavaScript, you might want to get the hang of CSS and HTML. – Bram Vanroy Nov 03 '13 at 09:05

3 Answers3

2

Ids should be unique. You want to use a class instead.

<div class="teststyle1">Test Text, 1-1</div>
<div class="teststyle1">Test Text, 1-2</div>

<button type="button" onclick="Array.prototype.forEach.call(document.getElementsByClassName('teststyle1'), function(element) { element.style.color='red'; })"> Test 1 </button>

Though for readability and good style, I recommend:

<div class="teststyle1">Test Text, 1-1</div>
<div class="teststyle1">Test Text, 1-2</div>

<button id="my_button" type="button"> Test 1 </button>
<script>
    document.getElementById('my_button').onclick = function() {
        Array.prototype.forEach(document.getElementsByClassName('teststyle1'), function(element) {
            element.style.color='red';
        });
    };
</script>
Paul Draper
  • 78,542
  • 46
  • 206
  • 285
  • `NodeList` does not inherit the Array prototype, and as such, does not have a `forEach` method. You can make it into an array with `[].slice.call`. – Niklas Nov 03 '13 at 09:00
0

You should not use ids on different elements. Try using class and then javascript will change all elements under the class

0

id is unique it's always apply first matching if you want go for class

<div class="class1">Test Text, 1-1</div>
<div class="class1">Test Text, 1-2</div>

in jquery you can access based on index

$('.class1:eq(0)').html();
$('.class1:eq(1)').html();