Home > Mobile >  How to add a h1 header with a message using javascript ( The code below is a new year 2023 countdown
How to add a h1 header with a message using javascript ( The code below is a new year 2023 countdown

Time:01-03

When the countdown comes to end i want to make h1[1] and h1[2] header visible and hide h1[0] hide. I did in a way given below in javasript code segment but h1[1] and h1[2] is not getting visible. Please someone point out my error and how to fix it?

JAVASCRIPT

document.body.querySelector("h1").textContent = "HAPPY NEW YEAR";
document.body.getElementsByTagName("h1")[1].style.display = inline; //Not working
document.body.getElementsByTagName("h1")[2].style.display = inline; //Not working

HTML

<body>
    <h1>New Year Countdown</h1>
    <h1 style="display:none">HAPPY NEW YEAR</h1>
    <br>
    <h1 style="display:none">WELCOME 2023!</h1>
    <div  id="countdown">
        <div  id="time">
            <div  id="days">
                <h2>00</h2>
                <h6>DAYS</h6>
            </div>
            <div  id="hours">
                <h2>00</h2>
                <h6>HOURS</h6>
            </div>
            <div  id="minutes">
                <h2>00</h2>
                <h6>MINUTES</h6>
            </div>
            <div  id="seconds">
                <h2>00</h2>
                <h6>SECONDS</h6>
            </div>
        </div>
    </div>
    <script src="source.js"></script>
</body>

CodePudding user response:

you can add an ID to your H1 and use getElementsById('h1-id')

and then update visibility: hidden css style property.

CodePudding user response:

i understand the problem you are facing. first of try removing in-line css that you are applying in the html file and shift that to the <style></style> inside the <header></header> section of the html document, we do this because inline-css is provided more importance than other form of style you inject in the document.

html

<h1  id="new_year_cntdwn">New Year Countdown</h1>
<h1 >HAPPY NEW YEAR</h1>
<br>
<h1 >WELCOME 2023!</h1>

Add the css

.headers{
        display: none;
    }
    #new_year_cntdwn{
        display: inline;
    }

And for the JavaScript Portion try using this after removing the inline css

Here we iterate through the array (here the header array that is being selected) if you want more information on querySelectorAll or forEach methods try reffering to https://developer.mozilla.org/en-US/

document.querySelectorAll(".headers").forEach(header=>header.style.display="block")
document.querySelector("#new_year_cntdwn").style.display="none"
  • Related