How to target .style attribut with .querySelectorAll selector?

前端 未结 2 1020
一整个雨季
一整个雨季 2021-01-23 16:14

I have selected a specific class via .querySelectorAll:

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

I am now

相关标签:
2条回答
  • 2021-01-23 17:03

    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>

    0 讨论(0)
  • 2021-01-23 17:11

    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.

    0 讨论(0)
提交回复
热议问题