Método jQuery attr()

❮ Métodos jQuery HTML/CSS

Ejemplo

Establezca el atributo de ancho de una imagen:

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

Definición y uso

El método attr() establece o devuelve atributos y valores de los elementos seleccionados.

Cuando se usa este método para devolver el valor del atributo, devuelve el valor del PRIMER elemento coincidente.

Cuando se utiliza este método para establecer valores de atributo, establece uno o más pares de atributo/valor para el conjunto de elementos coincidentes.


Sintaxis

Devolver el valor de un atributo:

$(selector).attr(attribute)

Establezca el atributo y el valor:

$(selector).attr(attribute,value)

Establecer atributo y valor usando una función:

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

Establezca múltiples atributos y 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

Pruébelo usted mismo - Ejemplos


de atributo Cómo devolver el valor de un atributo para un elemento.


Cómo usar una función para establecer el valor del atributo para un elemento.


Cómo establecer múltiples atributos/valores para un elemento.


❮ Métodos jQuery HTML/CSS