As a popular JavaScript library, jQuery has the ability to conveniently and efficiently operate DOM elements. Setting attributes for elements is also one of its commonly used functions. In this article, we will discuss several commonly used property setting methods and illustrate them with specific examples.
Use Use the ## The #prop() data() attr() attr() prop() data() attr() The above is the detailed content of jquery sets attributes to elements. For more information, please follow other related articles on the PHP Chinese website!attr()
method to set attributes and values for elements. For example, the following code sets theid
attribute for amyDiv
.
$('div').attr('id', 'myDiv');
attr()
method to set multiple attributes and values at the same time, for example:$('div').attr({ id: 'myDiv', class: 'box' });
2. Use the prop method
method is similar to the
attr()method and can set the attributes and values of the element, but there are some subtle differences between them.
prop()is mainly used to set the attributes of the element itself, such as
checked,
selected,
disabled, etc., while
attr( )is more suitable for setting non-standard attributes of elements. For example, the following code sets an input element to the selected state:
$('input[type="checkbox"]').prop('checked', true);
method to set data attributes for an element. Its syntax is very simple, you only need to pass the attribute to be set and the corresponding value as parameters. For example, the following code sets the
data-valueattribute of a
element to
100:
$('div').data('value', 100);
and
data()methods to also set custom attributes, which end with
data-starts. For example, the following code sets the custom attributes
data-countand
data-pricefor a
element:
$('div').attr('data-count', 10); $('div').data('price', 100);
method to obtain the attribute value of the element. For example, the following code obtains the
idattribute value of a
element:
var idValue = $('div').attr('id'); console.log(idValue); // 输出 'myDiv'
method to get the attribute value of an element. For example, the following code gets the selected status of a checkbox element:
var isChecked = $('input[type="checkbox"]').prop('checked'); console.log(isChecked); // 输出 true 或 false
method to obtain the data attribute value of an element. For example, the following code obtains the
data-valueattribute value of a
element. :
var dataValue = $('div').data('value'); console.log(dataValue); // 输出 100
method is suitable for setting non-standard attributes, the
prop()method is suitable for setting the attributes of the element itself, and the
data()method is suitable for setting and Get the data attribute of the element. Proficient use of these methods can make it easier for us to manipulate DOM elements and improve development efficiency.