Método HTML DOM hasAttribute()
❮ O Objeto ElementoExemplo
Descubra se um elemento <button> possui um atributo onclick:
var x = document.getElementById("myBtn").hasAttribute("onclick");
Mais exemplos de "Experimente você mesmo" abaixo.
Definição e uso
O método hasAttribute() retorna true se o atributo especificado existir, caso contrário, retorna false.
Dica: Use setAttribute() para adicionar um novo atributo ou alterar o valor de um atributo existente em um elemento.
Suporte ao navegador
Os números na tabela especificam a primeira versão do navegador que oferece suporte total ao método.
Method | |||||
---|---|---|---|---|---|
hasAttribute() | Yes | 9.0 | Yes | Yes | Yes |
Sintaxe
element.hasAttribute(attributename)
Parâmetros
Parameter | Type | Description |
---|---|---|
attributename | String | Required. The name of the attribute you want to check if exists |
Detalhes técnicos
Valor de retorno: | Um booleano, retorna true se o elemento tiver atributos, caso contrário, false |
---|---|
Versão DOM | Objeto de elemento de nível principal 2 |
Mais exemplos
Exemplo
Descubra se um elemento <a> tem um atributo target. Em caso afirmativo, altere o valor do atributo target para "_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
Referência HTML DOM: método getAttribute()
Referência HTML DOM: método removeAttribute()
Referência HTML DOM: método setAttribute()
❮ O Objeto Elemento