How to write $('label.someClass').attr('valid', true); in Java Script with out using jQuery?
5 Answers
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.
1 Comment
jAndy
please specify a reason for downvoting. If I made a mistake, help me and other guys out.
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);
}
}
4 Comments
Quentin
And you've got a
, where you should have a ;ajax333221
why not simply use
getElementsByClassName()?ShankarSangoli
@Quentin - Fixed both of them.
ShankarSangoli
@ajax333221 - Because it is not supported by all the classes. Though we can check for it and use it accordingly.
document.getElementById("myimage").setAttribute("src","another.gif")
Use the setAttribute() method (doc).
4 Comments
Quentin
What about finding all the label elements which are members of the someClass class?
eomeroff
How to select label by class in pure Java Script?
Quentin
In pure JavaScript? You can't. You need a DOM API. (OK, so I hate the term 'pure')
Nick Bork
getElementsByClassName though you will want to check to make sure it is avalaible in all browser versions. You could have to loop through each and check to see if the type if a lable. OR you can use getelementsbytagname and loop through them to find the class.
validattribute for<label>elements.