Adding attribute in jQuery

JqueryHtmlTags

Jquery Problem Overview


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" />

Jquery Solutions


Solution 1 - Jquery

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);

Solution 2 - Jquery

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.

Solution 3 - Jquery

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");

Solution 4 - Jquery

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

Solution 5 - Jquery

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

Solution 6 - Jquery

Add attribute as:

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

Solution 7 - Jquery

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

Solution 8 - Jquery

Use this code:

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

Solution 9 - Jquery

This could be more helpfull....

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

Solution 10 - Jquery

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYuda PrawiraView Question on Stackoverflow
Solution 1 - JqueryPaul RosaniaView Answer on Stackoverflow
Solution 2 - JquerydiEchoView Answer on Stackoverflow
Solution 3 - JquerymattsvenView Answer on Stackoverflow
Solution 4 - JqueryJerad RoseView Answer on Stackoverflow
Solution 5 - Jquerye382df99a7950919789725ceeec126View Answer on Stackoverflow
Solution 6 - Jqueryamar ghodkeView Answer on Stackoverflow
Solution 7 - JquerymorgarView Answer on Stackoverflow
Solution 8 - JqueryVildan BinaView Answer on Stackoverflow
Solution 9 - JqueryRejwanul RejaView Answer on Stackoverflow
Solution 10 - JqueryNakendra PunView Answer on Stackoverflow