Question

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

Was it helpful?

Solution

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); 
    }
}

OTHER TIPS

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.

Using a regular expression to match the class:

var labels = document.getElementsByTagName('label');
for(var i = 0;i<labels.length;i++){
    var classes = labels[i].className;
    if(classes && classes.match(/^(\s*|.*\s+)someClass(\s*|\s+.*)$/)){
         labels[i].setAttribute('valid', true); 
    }
}
document.getElementById("myimage").setAttribute("src","another.gif")

Try this Tutorial

Use the setAttribute() method (doc).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top