How to write $('label.someClass').attr('valid', true);
in Java Script with out using jQuery?
Array.prototype.forEach.call(document.querySelectorAll('label.someClass'), function( label ) {
label.setAttribute('someAttribute', 'someValue');
});
which implies that the browser is capable of ES5. An alternative for .querySelectorAll
could be .getElementsByClassName
too here.
Find all the label
elements using getElementsByTagName
which gives an array of matching elements. Run a loop on this array and check if the class name exists and set the attribute using setAttribute
method.
if(document.getElementsByClassName){
}
else{
var labels = document.getElementsByTagName('label');
for(var i = 0;i<labels.length;i++){
if(new RegExp("\\bsomeClass\\b", "g").test(labels[i].className)){
labels[i].setAttribute('valid', true);
}
}
If the browser supports getElementsByClassName
then we can use that conditionally.
if(document.getElementsByClassName){
var elements = document.getElementsByClassName('someClass');
for(var i = 0;i<elements.length;i++){
ifelements[i].tagName.toLowerCase() == 'label'){
elements[i].setAttribute('valid', true);
}
}
else{
var labels = document.getElementsByTagName('label');
for(var i = 0;i<labels.length;i++){
if(new RegExp("\\bsomeClass\\b", "g").test(labels[i].className)){
labels[i].setAttribute('valid', true);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With