Get the App
SLTechnology News&Howtos  ›  Development  › 

How jquery adds attribute values to elements

Shulou Source: shulou.com Published: 2022-06-02 11:40:03 09月11日 Update

This article focuses on "how to add attribute values to elements by jquery". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how jquery adds attribute values to elements.

Jquery add attribute value to the element method: 1, use the "$(element)" statement to get the specified element object; 2, use the attr () method to add attributes and values to the obtained element, the syntax is "element object .attr (attribute,value)".

The operating environment of this tutorial: windows7 system, jquery1.10.0 version, Dell G3 computer.

How jquery adds attribute values to elements

In jQuery, you can use the attr () method to increase the attribute value of the element, and the attr () method to set or return the attribute value of the selected element. The working mode of the method is also different according to the different parameters of the method. Returns the attribute value of the selected element.

The syntax of this method is:

$(selector) .attr (attribute,value)

Attribute specifies the property whose value you want to get.

Let's take a look at how to add attribute values to an element through an example, as follows:

We add a div to the html, and the div has only the class attribute. Then add a button to trigger the event that adds the property. Then introduce the jquery script into html. Then add a function, a function for button events, to script.

The function is simple, just use the attr method of jquery to set the property. The first parameter is the name of the property to be added, and the second is the value of the property. Here we add an id attribute for div.

Add the attribute function setAttr () {$(".jquery") .attr ("id", "bd");}

After running the page, from the source code of the page, the div now has no id attribute.

Click the button on the page to trigger the event and add the id attribute to the div.

After clicking, and then looking at the source code, you can see that you have successfully added an id attribute to div.

At this point, I believe you have a deeper understanding of "how jquery adds attribute values to elements". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Properties elements methods events buttons pages content functions parameters objects source code examples syntax learning different practical deeper success interest only Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Redmi Shulou Tech Info Docker MySQL