Change style of all of one HTML element using Javascript

时间:2017-10-12 10:15:17

标签: javascript html css

I can apply an opacity to all divs with some simple CSS:

div {
  opacity: 1;
}

But, how can I change the opacity of all divs dynamically using Javascript?

I've tried the following to no avail:

document.getElementById("div").style.opacity = 0.5;

Predictably so, as this targets elements with an ID...

Is there a way, using Javascript, that I can edit the style applied to all divs?

Thanks.

2 个答案:

答案 0 :(得分:1)

getElementsByTagName and querySelectorAll can get you a list of elements which share a tag name. You can then loop over it like an array.

A better bet would be to predefine your styles in CSS using a class on the body and a descendant selector, and then toggle that class with JavaScript.

div { opacity: 1; }
body.foo div { opacity: 0.5; }

and

document.body.classList.add("foo");

答案 1 :(得分:0)

You need to select all div by querySelectorAll and then loop.

function changeOpacity(){
  var divs = document.querySelectorAll("div");
  divs.forEach(function(elem){
    elem.style.opacity = 0.5;
  });
}
<div>
Niklesh
</div>
<div>
Raut
</div>
<input type="button" onclick="changeOpacity()" value="Change Opacity">