how to add and remove attribute using jQuery

how to add and remove attribute using jQuery

Hi, in this article we will discuss how to add and remove any attribute of an HTML element using jquery.

Table of contents:

  • Adding an attribute
  • Multiple attributes adding at once
  • how to get an attribute value
  • remove an attribute
  • removing multiple attributes at once

Add attribute

We will use the attr() function of jquery to add an attribute inside of an element.

Adding an attribute

.attr("attribute name","attribute value")
<input type="checkbox">

<script>
$(document).ready(function(){
  $("input[type='checkbox']").attr("checked","checked");
});
</script>
Browser Output

Adding multiple attributes at once

.attr({"name":"value","name":"value",....})
<input type="checkbox">
<script>
$(document).ready(function(){
  $("input[type='checkbox']").attr({
    "checked":"checked",
    "disabled":"disabled"
  });
});
</script>
Browser Output

How to get an attribute value

<input type="checkbox" data-id="5d23">

<script>
$(document).ready(function(){
  var attr_value = $("input[type='checkbox']").attr("data-id");R
  console.log(attr_value);
});
</script>

Result on console

5d23

Remove attribute

To remove an attribute we will use Jquery inbuilt function that isremoveAttr().

This remove attribute function accepts one argument that is an attribute name. removeAttr('attribute-name')

<p style="color:red;">Some text</p>
 
<script>
$(document).ready(function(){
  $("p").removeAttr("style");
});
</script>
Browser Output
Some text

Remove multiple attributes at once

<input type="checkbox" data-id="5d23" checked="checkbox" disabled="disabled">

<script>
$(document).ready(function(){
  $("input[type='checkbox']").removeAttr("checked disabled data-id");
});
</script>
Browser Output

Read also:

Posts Navigation


Leave a Reply

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