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" />
To set an attribute and value by using a function using this below syntax. $(selector). attr(attribute,function(index,currentvalue)) ; To set multiple attributes and values using this below syntax.
The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element. When this method is used to set attribute values, it sets one or more attribute/value pairs for the set of matched elements.
To retrieve a data-* attribute value as an unconverted string, use the attr() method. Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API. $( "div" ).
$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With