Home > Mobile >  TypeError: Cannot read properties of null (reading 'style') at hanldeClick
TypeError: Cannot read properties of null (reading 'style') at hanldeClick

Time:09-27

i want to change my target div variable display property none to block 

const userListEl = document.getElementById('user-list').innerHTML;
const template = Handlebars.compile(userListEl);
const targetDiv = document.getElementById("userDetail");


fetch("https://5dc588200bbd050014fb8ae1.mockapi.io/assessment")
    .then(response => response.json())
    .then((data) => {
        var userData = template({ usersList: data })
        document.getElementById('test').innerHTML = userData;
    }).catch((error) => {
        console.log(error)
    })

 this is my function

const hanldeClick =  () => {
    if (targetDiv.style.display === "none") {
        targetDiv.style.display = "block";
        
    } else {
        targetDiv.style.display = "none";
    }
 
};
#userDetail {
    display: none;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Exercise 1</title>
</head>

<body>
    <div id="test"></div>
    <script id="user-list" type="text/x-handlebars-template">
        <ul class="people_list"> {{#each usersList}} 
            <li>                
                <p class="">{{name}}</p>
                <img src={{avatar}} alt={{name}}>
                <div id="userDetail">
                    <p>Id: {{id}}</p>
                     <p>Created at: {{createdAt}}</p>
                 </div>
                <button onclick="hanldeClick()"> Detail </button>
            </li>
             {{/each}} 
            </ul>
          
    </script>
    <script type="text/javascript" src="app.js" defer></script>
    <script src="https://cdn.jsdelivr.net/npm/handlebars@latest/dist/handlebars.js"></script>

</body>
i want to change display none to block on onclick but when button clicked "TypeError: Cannot read properties of null (reading 'style') " this error occured Can someone help me?

CodePudding user response:

It is possible that your targetDiv is undefined. You can modify your handleClick as below.

const hanldeClick = () => {
  if (targetDiv) {
    if (targetDiv.style.display === "none") {
      targetDiv.style.display = "block";

    } else {
      targetDiv.style.display = "none";
    }
  }
};

In addition to that you're calling the handleClick instead of passing it.

The button code should be like this

<button onclick="hanldeClick"> Detail </button>

CodePudding user response:

targetDiv is null when you click the "Detail" button and trigger the handleClick function because there is no DOM element with the id userDetail when you invoke document.getElementById("userDetail");.

To verify this, you could log the value of targetDiv immediately after your assignment:

const targetDiv = document.getElementById("userDetail");
console.log(targetDiv); // null

Why is <div id="userDetail"> not a DOM element?

Because it is a part of a template within a script tag. The type="text/x-handlebars-template" attribute you have added to your script block is basically telling the browser to ignore what it contains. This is what allows you to add arbitrary content, like the mustaches understood by the Handlebars library. For more on this: see Explanation of <script type = "text/template"> ... </script>

In order for your code to reference the DOM element with id userDetail, you will need to get it from the DOM after you have injected your template-rendered HTML into document - ie., after you set the innerHTML of #test to userData:

let targetDiv = null;

fetch("https://5dc588200bbd050014fb8ae1.mockapi.io/assessment")
    .then(response => response.json())
    .then((data) => {
        var userData = template({ usersList: data })
        document.getElementById('test').innerHTML = userData;
        targetDiv = document.getElementById("userDetail");
    }).catch((error) => {
        console.log(error)
    })

I have created a fiddle for your reference.

Additionally, even with this fix, I think you are going to find that your code does not work as you intend. It looks like you want handleClick to toggle a sibling <div> - and that this should be the effect for each <li> in your <ul>. However, your document.getElementById("userDetail") will return only the first element with id userDetail, so no matter which "Detail" <button> is clicked, only the first <li>'s detail will be toggled. You will need to find a way to specify to your handler which detail to toggle.

  • Related