Método jQuery attr()

❮ Métodos jQuery HTML/CSS

Exemplo

Defina o atributo de largura de uma imagem:

$("button").click(function(){
  $("img").attr("width","500");
});

Definição e uso

O método attr() define ou retorna atributos e valores dos elementos selecionados.

Quando este método é usado para retornar o valor do atributo, ele retorna o valor do PRIMEIRO elemento correspondente.

Quando esse método é usado para definir valores de atributo, ele define um ou mais pares de atributo/valor para o conjunto de elementos correspondentes.


Sintaxe

Retorna o valor de um atributo:

$(selector).attr(attribute)

Defina o atributo e o valor:

$(selector).attr(attribute,value)

Defina o atributo e o valor usando uma função:

$(selector).attr(attribute,function(index,currentvalue))

Defina vários atributos e valores:

$(selector).attr({attribute:value, attribute:value,...})

Parameter Description
attribute Specifies the name of the attribute
value Specifies the value of the attribute
function(index,currentvalue) Specifies a function that returns the attribute value to set
  • index - Receives the index position of the element in the set
  • currentvalue - Receives the current attribute value of selected elements

Experimente você mesmo - Exemplos


Como retornar o valor de um atributo para um elemento.


Como usar uma função para definir o valor do atributo para um elemento.


Como definir vários atributos/valores para um elemento.


❮ Métodos jQuery HTML/CSS