-3

I want to use getElementById("xxx").style.color = "xxx". With this I want to change some css value. But the problem is when i use this and test all same id with this but it does't effect all id and effects only the first one.

Sample code is as follow:

<html>
<body>
<div id = "test">Test</div>
<div id = "test">Test</div>
<div id = "test">Test</div>
<div id = "test">Test</div>
<script>
     document.getElementById("test").style.color = "blue"
</script>
</body>
</html>

What should i do to change all 4 Test to color blue.
AnyIdea pls.
Thanks

4 Answers4

7

An ID must be unique in an HTML document. Write valid HTML.

To represent multiple, related elements: use a class.

You can then use getElementsByClassName or querySelectorAll to get an array-like object which you can use a for loop to access each element in turn.

var elements = document.querySelectorAll(".test");
for (var i = 0; i < elements.length; i++) {
  elements[i].style.color = "blue";
}
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>

Alternatively, write a stylesheet with a descendant combinator and toggle the classes on a containing element.

document.getElementById("container").classList.add("foo");
.test { color: black; }
.foo .test { color: blue; }
<div id="container">

  <div class="test">Test</div>
  <div class="test">Test</div>
  <div class="test">Test</div>
  <div class="test">Test</div>

</div>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

As stated before, an ID must be unique. If you want to give multiple DOM-elements the same style just use 'class'. you could try this:

<html>

<body>
  <div class="test">Test</div>
  <div class="test">Test</div>
  <div class="test">Test</div>
  <div class="test">Test</div>
  <script>
    var divList = document.getElementsByClassName("test");
    for (var i = 0; i < divList.length; i++) {
      divList[i].style.color = "red";
    }
  </script>
</body>

</html>

to change the style using javascript.

ThomasS
  • 705
  • 1
  • 11
  • 30
0

There are two problems with your code :

  • id must be unique, so you should use eg. class instead
  • you should loop across the different elements that are selected

This is my prefered way to correct those two problems :

<html>
  <body>
    <div class="test">Test</div>
    <div class="test">Test</div>
    <div class="test">Test</div>
    <div class="test">Test</div>
    <script>
        Array.prototype.slice.call(
            document.getElementsByClassName("test")
        ).forEach(function(element) {
            element.style.color = "blue"
        });
    </script>
  </body>
</html>

See also this Fiddle.

John Slegers
  • 45,213
  • 22
  • 199
  • 169
-2

For jQuery Solution

You cannot use same id for performing same operation on all the elements

You can use class name and add style using jquery like

 $(".className").css("color","blue");
Kirankumar Dafda
  • 2,354
  • 5
  • 29
  • 56