Skip to content
Advertisement

How to change the id of an element in html using javascript?

It is my first time using JavaScript. I am trying to make a button where every time visitors click, it’ll show another extra line of text. I often get an error on my JavaScript, and I’m not sure how to fix it. Thank you so much!

HTML;

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
    <div class="container">
        <div class="text">
            <div class="one hide">
                One            
            </div>
            <div class="two hide">
                Two
            </div>
            <div class="three hide">
                Three
            </div>
        </div>
        <a href="#" class="button" id="hr1"></a>
    </div>
</body>
<script src="script.js"></script>
</html>

JS;

const text = document.querySelector('.text');
const hide = document.querySelector('.hide');
const one = document.querySelector('.one');
const two = document.querySelector('.two');
var hr1 = document.getElementById('hr1');
var hr2 = document.getELementById('hr2');
var hr3 = document.getElementById('hr3');

hr1.addEventListener('click', () => {
    one.classList.remove('hide');
    hr1.id = "hr2"; 
})

// I often get an error on hr2.addEventListener
hr2.addEventListener('click', () => {
    two.classList.remove('hide');
    hr2.id = "hr3";
})

Advertisement

Answer

Your code throws error because you are trying to set hr2 and hr3 when they are not exist. You need to set hr2 and hr3 variables after setting id’s of them like below:

hr1.id = "hr2"; 
hr2= document.getElementById('hr2');

const text = document.querySelector('.text');
const hide = document.querySelector('.hide');
const one = document.querySelector('.one');
const two = document.querySelector('.two');
var hr1 = document.getElementById('hr1');
var hr2 = null;
var hr3 = null;
hr1.addEventListener('click', () => {
    //one.classList.remove('hide');
    hr1.id = "hr2"; 
    hr2= document.getElementById('hr2');
    console.log(hr2);
    hr2.addEventListener('click', () => {
      two.classList.remove('hide');
      hr2.id = "hr3";
      hr3 = document.getElementById('hr3');
      console.log(hr3);
  })
})

// I often get an error on hr2.addEventListener
    <div class="container">
        <div class="text">
            <div class="one hide">
                One            
            </div>
            <div class="two hide">
                Two
            </div>
            <div class="three hide">
                Three
            </div>
        </div>
        <a href="#" class="button" id="hr1">clickme</a>
    </div>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement