5

I'm trying to addclass to all elements at once using html dom. // No jquery

Here is what i tryed:

document.getElementsByTagName("*").classList.add('addedclassname');

I guess i could not select(get) all elements. Because this,

document.getElementById("id").classList.add('addedclassname');

was working.

  • `document.getElementByTagName("*")` returns collection of elements but `classList` is a property of single `Element`... You are suppose to loop through all the elements.. I feel `getElementsById` mentions in OP is typo.. – Rayon Dec 08 '17 at 12:07
  • 1
    `[].forEach.call(document.getElementsByTagName("*"),function(el){ el.classList.add('addedclassname'); });` should work... – Rayon Dec 08 '17 at 12:09
  • How can i do this at once? – Tuvshintsenguun Dec 08 '17 at 12:09
  • You have a collection, to attach property to each element, you will have to loop them... – Rayon Dec 08 '17 at 12:12
  • As suggested above, you will have to loop through the node list/collection but I would also recommend you use `document.getElementsByTagName('body')[0].getElementsByTagName('*');` otherwise you will be adding a `class` to all tags ` – NewToJS Dec 08 '17 at 12:19

3 Answers3

1

You just need to iterate each element like this

    var els = document.getElementsByTagName("*");
    for(var i = 0, all = els.length; i < all; i++){   
         els[i].classList.add('addedclassname');
     }
Goms
  • 2,424
  • 4
  • 19
  • 36
1

You should iterate them;

var elementList = document.getElementsByTagName("*");
for(var i = 0; i < elementList.length; i++)
{
    elementList[i].classList.add('addedclassname');
}
lucky
  • 12,734
  • 4
  • 24
  • 46
-1

function addClass(){
document.getElementsByTagName("*")[0].setAttribute("class", "demo")
}
.demo {
    color: red;
}
<h1>this is h1 element</h1>
<p>hello this is p element</p>
<h2>this is h2 element</h2>
<button onclick='addClass()'>add class</button>
vicky patel
  • 699
  • 2
  • 8
  • 14