To create a class to a existing element using jquery

When ever different changes is to be made to a single element we create class to an existing div using jquery

To add a new class, we use jQuery addClass() method. The addClass() method is used to add more classes and their attributes to each selected element.

It can also be used to change the property of the selected element.

Syntax: $(selector).addClass(className);

Ex 1:

<script>
$(document).ready(function () {$("button").click(function () {$("p").addClass("GFG2");});});
</script>
.GFG1 {
            color: green;
            font-weight: bold;// existing class
        }
  
        .GFG2 {
            font-size: 24px;// new class added to execute based on condition
        }

Ex 2: Used in pdp extension tpl file

 <script>
var inputs = document.querySelectorAll('.product-views-option-text-input')    inputs.forEach(input => {      
input.addEventListener('blur', (e) => {        
if (e.target.value.trim().length == 0) {        
  e.target.classList.add('warning')       
 } else {         
 e.target.classList.remove('warning')       
 }     
 })    
})  
});
</script>
css
.warning 
{
    border: 1px solid red;
}

Leave a comment

Your email address will not be published. Required fields are marked *