How to target .style attribut with .querySelectorA

2020-04-21 02:00发布

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

2条回答
劳资没心,怎么记你
2楼-- · 2020-04-21 02:06

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>

查看更多
仙女界的扛把子
3楼-- · 2020-04-21 02:27

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.

查看更多
登录 后发表回答