HTML :
JavaScript
x
2
1
<input type="checkbox" aria-checked="false" class="cloud-private" value="" data-spm-anchor-id="a800.io">
2
My java script : ( i want to click this checkbox if it is not checked ,but this does not work )
JavaScript
1
5
1
var z = document.getElementsByClassName('cloud-private');
2
if (z[0].aria-checked=='false'){
3
z[0].click();
4
}
5
Advertisement
Answer
Should not be using aria-checked
here in this way. Should be using the checked
attribute as is shown in the checkbox spec on MDN.
JavaScript
1
6
1
let cloudPrivateCbxs = document.querySelectorAll('.cloud-private');
2
3
if (cloudPrivateCbxs && !cloudPrivateCbxs[0].checked) {
4
cloudPrivateCbxs[0].click();
5
}
6
Here I used a useful variable names (never use single letter variable names except for simple counters like those in for
loops), used querySelectorAll
instead of getElementsByClassName
, then I first check if the variable contains anything, then I simply check the checked
attribute to see if it returns false. It is returning a boolean so I can use the logical NOT operator !
rather than check directly if it is equal to false.