EN VI

Javascript - The code seems to be fine, but not getting the output. Expected output : Replace text "Heading 1" on browser with array from new.js file?

2024-03-10 00:00:08
How to Javascript - The code seems to be fine, but not getting the output. Expected output : Replace text "Heading 1" on browser with array from new.js file

I have 2 files index.html and new.js but could not get the output on browser as expected. The error shows on document.getElementById("h1").innerHTML=fruits; //fruits: name of the array also tried document.getElementById("h1").innerHTML= fruits.join(", "); //got this from chat gpt

//new.js file content

let fruits=["apple","orange","mango"];
fruits.push("kiwi", "grape")
console.log(fruits);
let f1= fruits.indexOf("kiwi");
console.log(f1);
document.getElementById("h1").innerHTML= fruits.join(", ");

//index.html file content

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./new.js"></script>
</head>
<body>
    <h1 id="h1">Heading 1</h1>
    
</body>
</html>

Solution:

You try to infer attributes of an element before it exists. You need to make sure your Javascript runs after your HTML element was created. A way to achieve this is to create a load event handler that runs when the page has loaded and by that time your HTML element was also created. I therefore wrapped a load event handler around your code.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
    window.addEventListener('load', function() {
        let fruits=["apple","orange","mango"];
        fruits.push("kiwi", "grape")
        console.log(fruits);
        let f1= fruits.indexOf("kiwi");
        console.log(f1);
        document.getElementById("h1").innerHTML= fruits.join(", ");
    });
    </script>
</head>
<body>
    <h1 id="h1">Heading 1</h1>
    
</body>
</html>

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login