How to target .style attribut with .querySelectorA

2020-04-21 02:14发布

问题:

I have selected a specific class via .querySelectorAll:

var hit3 = document.querySelectorAll(".lattern.hit-3 .circle");

I am now trying to target and adjust a .style.visibility attribut on this element, by doing the following:

hit3.style.visibility = "visible";

This however results in an error:

Uncaught TypeError: Cannot set property 'visibility' of undefined

How do I target a specific .style with the above .querySelectorAll selector?

Fiddle

回答1:

querySelectorAll return a node list so you should specify the index of element you want to change :

hit3[0].style.visibility = "visible";

If you want to change the css of all the elements returned you should loop through them, see Johny's answer.

Hope this helps.



回答2:

querySelectorAll returns an array like structure(NodeList) which does not have the style attribute.

But I think what you need is slightly different, I assume want to display the circle for the clicked element then

var latternElement = document.querySelectorAll('.lattern');

function toggleElement(el) {
  el.querySelector('.circle').classList.add('visible'); //also minor tweaks, use css rules
}

for (var i = 0; i < latternElement.length; i++) {
  latternElement[i].addEventListener('click', function(event) {
    if (this.classList.contains("hit-3")) { //minor tweaks - only supported in modern browsers
      toggleElement(this);
    }
  });
}
.lattern {
  position: relative;
  width: 100px;
  height: 50px;
  background-color: red;
  margin: 0 0 10px 0;
  cursor: pointer;
}
.circle {
  position: relative;
  top: 20px;
  left: 20px;
  border-radius: 50% 50%;
  width: 16px;
  height: 16px;
  background-color: green;
  visibility: hidden;
}
.circle.default,
.circle.visible {
  visibility: visible;
}
<div class="lattern hit-1">
  <div class="circle"></div>
</div>
<div class="lattern hit-2">
  <div class="circle default"></div>
</div>
<div class="lattern hit-3">
  <div class="circle"></div>
  click me
</div>