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 attr()
method to set attributes and values for elements. For example, the following code sets the id
attribute for a <div>
element with the value myDiv
.
$('div').attr('id', 'myDiv');
Use the attr()
method to set multiple attributes and values at the same time, for example:
$('div').attr({ id: 'myDiv', class: 'box' });
## The #prop() 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);
data() 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-value attribute of a
<div> element to
100:
$('div').data('value', 100);
attr() and
data() methods to also set custom attributes, which end with
data- starts. For example, the following code sets the custom attributes
data-count and
data-price for a
<div> element:
$('div').attr('data-count', 10); $('div').data('price', 100);
attr() method to obtain the attribute value of the element. For example, the following code obtains the
id attribute value of a
<div> element:
var idValue = $('div').attr('id'); console.log(idValue); // 输出 'myDiv'
prop() 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
data() method to obtain the data attribute value of an element. For example, the following code obtains the
data-value attribute value of a
<div> element. :
var dataValue = $('div').data('value'); console.log(dataValue); // 输出 100
attr() 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.
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!