Hello, Reader today we discuss the add class or attribute in jQuery.
Sometimes developers need to add a custom class or attribute on the element after the page load or clicked somewhere to perform functionality according to the need.
1. Add random class or attribute on the drop-down options
var counterOption = 0;
jQuery("select").each( function (){
counterOption++;
var rndmClass = 'hello_'+counterOption;
console.log(rndmClass);
jQuery(this).attr('data-value',rndmClass);
});
2. Add random class and attribute on all li tags.
var counter = 0;
jQuery("ol li" ).each( function (){
counter++;
var rndmClass = 'hello_'+counter;
console.log(rndmClass);
jQuery(this).addClass( rndmClass);
jQuery(this).attr('data-value',rndmClass);
});
3. Add some class on all li tags
jQuery("ol li").addClass('myclass');
4. Get attribute value in jQuery
var datavalue = jQuery("ol li").attr('data-value');
console.log(datavalue);
5. Drop down change event / Get selected option attribute value.
jQuery("select").change(function(){
var value = jQuery(this).children("option:selected").attr('data-value');
});
Related Post Add/Remove Class in Javascript