📜  jquery attr - Javascript (1)

📅  最后修改于: 2023-12-03 14:43:08.399000             🧑  作者: Mango

jQuery attr - JavaScript

Introduction

The attr() method in jQuery is used to get or set the value of the specified attribute for the selected elements. It provides a convenient way to manipulate attributes of HTML elements using JavaScript.

Syntax

The syntax to use attr() method is as follows:

$(selector).attr(attributeName)
$(selector).attr(attributeName, value)
  • selector is a string representing the HTML element(s) to be selected.
  • attributeName is a string representing the name of the attribute to be manipulated.
  • value (optional) is the new value to be assigned to the attribute.
Getting the Attribute Value

To retrieve the value of an attribute for the selected element(s), use the attr() method without specifying the value parameter. It returns the value of the specified attribute.

Example:

var idValue = $("p").attr("id");
console.log(idValue);

Markdown format:

```javascript
var idValue = $("p").attr("id");
console.log(idValue);

## Setting the Attribute Value
To set the value of an attribute for the selected element(s), use the `attr()` method and specify both the `attributeName` and `value` parameters.

Example:
```javascript
$("img").attr("src", "new_image.png");

Markdown format:

```javascript
$("img").attr("src", "new_image.png");

## Modifying Multiple Attributes
You can modify multiple attributes at once by passing an object as the `attributeName` parameter with key-value pairs representing attribute names and their corresponding values.

Example:
```javascript
$("a").attr({
  "href": "https://www.example.com",
  "target": "_blank"
});

Markdown format:

```javascript
$("a").attr({
  "href": "https://www.example.com",
  "target": "_blank"
});

## Removing an Attribute
To remove an attribute from the selected element(s), use the `removeAttr()` method with the `attributeName` parameter.

Example:
```javascript
$("input").removeAttr("disabled");

Markdown format:

```javascript
$("input").removeAttr("disabled");

## Conclusion
The `attr()` method in jQuery is a powerful tool for manipulating attributes of HTML elements in JavaScript. It allows you to get, set, modify, and remove attributes easily, enhancing the interactivity and functionality of your web pages.