Método HTML DOM hasAttribute()
❮ El Objeto ElementoEjemplo
Averigüe si un elemento <button> tiene un atributo onclick:
var x = document.getElementById("myBtn").hasAttribute("onclick");
Más ejemplos de "Pruébelo usted mismo" a continuación.
Definición y uso
El método hasAttribute() devuelve verdadero si existe el atributo especificado; de lo contrario, devuelve falso.
Sugerencia: use setAttribute() para agregar un nuevo atributo o cambiar el valor de un atributo existente en un elemento.
Compatibilidad con navegador
Los números en la tabla especifican la primera versión del navegador que soporta totalmente este método.
Method | |||||
---|---|---|---|---|---|
hasAttribute() | Yes | 9.0 | Yes | Yes | Yes |
Sintaxis
element.hasAttribute(attributename)
Parámetros
Parameter | Type | Description |
---|---|---|
attributename | String | Required. The name of the attribute you want to check if exists |
Detalles técnicos
Valor de retorno: | Un valor booleano, devuelve verdadero si el elemento tiene atributos; de lo contrario, devuelve falso |
---|---|
Versión DOM | Objeto de elemento de nivel básico 2 |
Más ejemplos
Ejemplo
Averigüe si un elemento <a> tiene un atributo de destino. Si es así, cambie el valor del atributo de destino a "_self":
// Get the <a> element with id="myAnchor"
var x = document.getElementById("myAnchor");
// If the <a> element has a target attribute, set the value to "_self"
if (x.hasAttribute("target")) {
x.setAttribute("target", "_self");
}
páginas relacionadas
Tutorial HTML: Atributos HTML
Referencia HTML DOM: Método getAttribute()
Referencia HTML DOM: método removeAttribute()
Referencia HTML DOM: Método setAttribute()
❮ El Objeto Elemento