La actividad inversa de agregar un atributo a una marca HTML se logra mediante el método removeAttribute.
Para ver el funcionamiento de este método implementaremos una página que muestra dos hipervínculos, luego mediante dos botones podemos crear o eliminar el atributo href de las respectivas marcas.
pagina.html
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Prueba</title>
</head>
<body>
<a id="enlace1" href="https://www.google.com.ar">Google.</a><br>
<a id="enlace2" href="https://www.yahoo.com.ar">Yahoo.</a><br>
<input type="button" value="Eliminar atributos" onClick="eliminarAtributo()">
<input type="button" value="Inicializar atributos" onClick="inicializarAtributo()">
<script src="funciones.js"></script>
</body>
</html>
funciones.js
function eliminarAtributo() {
let puntero = document.getElementById('enlace1')
puntero.removeAttribute('href')
puntero = document.getElementById('enlace2')
puntero.removeAttribute('href')
}
function inicializarAtributo() {
let puntero = document.getElementById('enlace1')
puntero.setAttribute('href', 'https://www.google.com.ar')
puntero = document.getElementById('enlace2')
puntero.setAttribute('href', 'https://www.yahoo.com.ar')
}
Lo nuevo se encuentra en la función eliminarAtributo.
Primero obtenemos la referencia del primer enlace cuyo id se llama enlace1:
let puntero = document.getElementById('enlace1')
Y ahora con la referencia a la marca HTML que se guardó en la variable puntero llamamos al método removeAttribute:
puntero.removeAttribute('href')
Lo mismo hacemos para el segundo enlace:
puntero = document.getElementById('enlace2')
puntero.removeAttribute('href')
Para crear el atributo lo hacemos como lo vimos en un concepto anterior:
let puntero = document.getElementById('enlace1')
puntero.setAttribute('href', 'https://www.google.com.ar')
puntero = document.getElementById('enlace2')
puntero.setAttribute('href', 'https://www.yahoo.com.ar')
Tengamos siempre en cuenta que podemos hacer un código más conciso sin la definición de variables donde almacenamos las referencias a las etiquetas (lo hacemos por el momento para que el código quede más entendible):
function eliminarAtributo() {
document.getElementById('enlace1').removeAttribute('href')
document.getElementById('enlace2').removeAttribute('href')
}
function inicializarAtributo() {
document.getElementById('enlace1').setAttribute('href', 'https://www.google.com.ar')
document.getElementById('enlace2').setAttribute('href', 'https://www.yahoo.com.ar')
}