Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

199
Views
TypeError: Cannot read properties of null (reading 'style') at handleClick

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.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 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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!