Get the App
SLTechnology News&Howtos  ›  Development  › 

How to get attributes by jquery

Shulou Source: shulou.com Published: 2022-06-01 03:58:51 11月11日 Update

This article mainly explains "how jquery obtains attributes". The explanation content in this article is simple and clear, easy to learn and understand. Please follow the ideas of Xiaobian slowly and deeply to study and learn "how jquery obtains attributes" together!

jquery commonly used methods to obtain attributes are: 1, attr() method, can obtain and return the value of the specified attribute, syntax "$(selector).attr(" attribute name ")";2, prop() method, can return the attribute value of the selected element, syntax "$(selector).prop(" attribute name ")".

This tutorial operates on Windows 7, jquery version 1.10.2, Dell G3 computers.

There are two common methods for jquery to obtain attributes:

attr() method

prop() method

jquery attr() method

The attr() method sets or returns the attribute value of the selected element.

Example: Get the value of img element width attribute

$(document).ready(function() { $("button").click(function() { alert("picture width is" + $("img").attr("width")); }); });

Returns the width of the image

jquery prop() method

The prop() method sets or returns the properties and values of the selected element.

When this method is used to return attribute values, it returns the value of the first matching element.

Examples:

$(document).ready(function() { $("button").click(function() { alert("picture width is" + $("img").prop("width")); }); });

Returns the width of the image

Difference between attr() and prop() methods

The prop() method is similar to the attr() method in that it is used to get or set HTML attributes of an element, but there are essential differences between the two.

jQuery official recommendation: properties with two values of true and false, such as checked, selected and disabled, are recommended to use the prop() method to operate, while other properties are recommended to use the attr() method to operate.

Thank you for reading, the above is "jquery how to obtain attributes" content, after the study of this article, I believe we have a deeper understanding of how to obtain attributes of jquery this problem, the specific use of the situation also needs to be verified by practice. Here is, Xiaobian will push more articles related to knowledge points for everyone, welcome to pay attention!

Tags: Attributes methods elements widths suggestions learning content images pictures commonly used examples grammar similarity two official that is ideas situations tutorials articles Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology NVidia MariaDB Apple macOS