- 5 years ago
- Zaid Bin Khalid
- 36,575 Views
-
6
You can add or remove multiple elements with the help of JQuery? In this post, I’ll share with you, how you can achieve the same in one go. Jquery makes Javascript easy to use on your web site.
What is JQuery?
“Write less, do more” JQuery is the lightweight plugin. Before starting you should have a piece of knowledge about
JQuery is very simple to use you just need to add JQuery plugin into your webpage. To download the latest JQuery Plugin click here.
There are so many other javascript libraries but JQuery is most popular among them.
You can add and remove multiple attributes with the help of JQuery by using the below code.
- $(selector).attr() use to add attributes into the HTML element.
- $(selector).removeAttr() use to remove attributes into the HTML element.
If you want to add multiple attributes into an HTML element you just need to pass all attributes separated by a comma. As shown in the above snippet.
<div class="col-sm-12 m-auto bg-light p-2">
<img src="https://www.placehold.it/250x250" class="img-thumbnail" id="img"></img>
<div class="mt-1">
<input type="submit" class="btn btn-primary" id="btn" value="Set Attribute">
<input type="reset" class="btn btn-danger" id="removebtn" value="Remove Attribute">
</div>
</div>
$(document).ready(function(){
$('#btn').on("click",function(){
$('#img').attr({
'src':'https://learncodeweb.com/wp-content/uploads/2019/01/php.jpg',
'width':'250',
'height':'250'
});
});
$('#removebtn').on("click",function(){
$('#img').attr('src','https://www.placehold.it/250x250');
$('#img').removeAttr('width height');
});
});
To a single attribute, you can write code like below.
//Add attribute
$('#img').attr('src','https://learncodeweb.com/wp-content/uploads/2019/01/php.jpg');
//Remove attribute
$('#img').removeAttr('width');
- 5 years ago
- Zaid Bin Khalid
- 36,575 Views
-
6