Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add attribute in in Javascript

How to write $('label.someClass').attr('valid', true); in Java Script with out using jQuery?

like image 343
eomeroff Avatar asked Feb 02 '12 16:02

eomeroff


2 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.

like image 92
jAndy Avatar answered Oct 16 '22 20:10

jAndy


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); 
    }
}
like image 1
ShankarSangoli Avatar answered Oct 16 '22 22:10

ShankarSangoli