Adding Attribute in jQuery

Adding Attribute in jQuery

How can I add an attribute into specific HTML tags in jQuery?

For example, like this simple HTML:

<input id="someid" />

Then adding an attribute disabled="true" like this:

<input id="someid" disabled="true" />
1

10 Answers

You can add attributes using attr like so:

$('#someid').attr('name', 'value');

However, for DOM properties like checked, disabled and readonly, the proper way to do this (as of JQuery 1.6) is to use prop.

$('#someid').prop('disabled', true);
4

best solution: from jQuery v1.6 you can use prop() to add a property

$('#someid').prop('disabled', true);

to remove it, use removeProp()

$('#someid').removeProp('disabled');

Reference

Also note that the .removeProp() method should not be used to set these properties to false. Once a native property is removed, it cannot be added again. See .removeProp() for more information.

You can do this with jQuery's .attr function, which will set attributes. Removing them is done via the .removeAttr function.

//.attr()
$("element").attr("id", "newId");
$("element").attr("disabled", true);

//.removeAttr()
$("element").removeAttr("id");
$("element").removeAttr("disabled");
2
$('#someid').attr('disabled', 'true');
$('#someid').attr('disabled', 'true');

Add attribute as:

$('#Selector_id').attr('disabled',true);
$('.some_selector').attr('disabled', true);

Use this code:

<script> 
   $('#someid').attr('disabled', 'true'); 
</script>
2

This could be more helpfull....

$("element").prop("id", "modifiedId");
//for boolean
$("element").prop("disabled", true);
//also you can remove attribute
$('#someid').removeProp('disabled');
1
$('#yourid').prop('disabled', true);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi
Author

Maya Lin-Takahashi

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.