javascript - TypeError: Cannot read properties of null (reading 'style') at handleClick - Stack Overflow

I want to change my target div variable's display property from none to block.const userListEl = d

I want to change my target div variable's display property from none to block.

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


fetch("")
    .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="@latest/dist/handlebars.js"></script>

</body>

I want to change my target div variable's display property from none to block.

const userListEl = document.getElementById('user-list').innerHTML;
const template = Handlebars.pile(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/npm/handlebars@latest/dist/handlebars.js"></script>

</body>

I want to change the display value none to block in an onclick handler, but when the button is clicked I get this error:

TypeError: Cannot read properties of null (reading 'style')

Can someone help me?

Share Improve this question edited Jun 21, 2022 at 13:29 76484 9,0033 gold badges21 silver badges32 bronze badges asked Sep 26, 2021 at 18:15 Ahsan HafeezAhsan Hafeez 311 gold badge2 silver badges5 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 1

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745253641a4618826.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信