How To Target .style Attribut With .queryselectorall Selector?
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 at
Solution 1:
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');
functiontoggleElement(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 browserstoggleElement(this);
}
});
}
.lattern {
position: relative;
width: 100px;
height: 50px;
background-color: red;
margin: 0010px0;
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;
}
<divclass="lattern hit-1"><divclass="circle"></div></div><divclass="lattern hit-2"><divclass="circle default"></div></div><divclass="lattern hit-3"><divclass="circle"></div>
click me
</div>
Solution 2:
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.
Post a Comment for "How To Target .style Attribut With .queryselectorall Selector?"