1

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";
})
1
  • Because there is not HTML element whose id is hr2 and hr3. Commented Jul 3, 2021 at 12:14

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.