Home >Web Front-end >JS Tutorial >How to add attributes to a li node in jquery
Method: 1. Use the "$(li element)" statement to match the li object; 2. Use the ":eq()" selector to select the specified li node, the syntax is "li object.eq (position value) "; 3. Use the attr() method to add attributes to the specified li node, the syntax is "li node.attr("new attribute name", "new attribute value")".
The operating environment of this tutorial: windows7 system, jquery1.10.0 version, Dell G3 computer.
How to add attributes to a certain li node in jquery
In jquery, you can select the specified index through the :eq() selector value element. Combined with the attr() method to set or return the attribute value of the selected element. The world can add attributes to a certain li node. The syntax of the attr() method is:
$(selector).attr(attribute)
Let's take an example to see how to add an attribute to a certain li node. The example is as follows:
1. Create a new html file and name it test.html, which is used to add the id attribute to the li tag using jquery. Use ul and li tags to create a list, and in each li, write text for testing. Use css to define a style with the id myli, which is used to confirm that the id attribute is added to li.
Use the button tag to create a button with the button name "Add id attribute". Bind the onclick click event to the button button. When the button is clicked, the addid() function is executed.
2. In the js tag, create the addid() function. Within the function, use the $ symbol to obtain the object through the element li, and use eq(1) to obtain the second one. li object, set the id attribute of li through the attr() method.
Open the test.html file in the browser and click the button to see the effect.
After clicking the button:
Summary:
1. Create a test.html file .
2. In the file, in the p tag, use the ul and li tags to create a list, and create a button button to trigger the execution of the js function.
3. Create a function in the js tag. Within the function, use the $ symbol to obtain the object through the element li, use eq(1) to obtain the second li object, and set the id of li through the attr() method. Attributes.
Note: The
attr() method can not only add the id attribute, but also obtain the id attribute value of an element.
Recommended related video tutorials: jQuery video tutorial
The above is the detailed content of How to add attributes to a li node in jquery. For more information, please follow other related articles on the PHP Chinese website!