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

166
Views
how to pass event in innerhtml by onclick

I am making a project about add to cart. I want to pass event by onclick from innerhtml.
Here is my html code

<!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" />
<title>Add to cart</title>
<link
  href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
  rel="stylesheet"
  integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
  crossorigin="anonymous"
/>
</head>
<body>
 <div id="cards-container" class="row align-items-center my-3 p-3"></div>
 <script src="./script.js"></script>
</body>
</html>

Here is my js code

fetch('https://jsonplaceholder.typicode.com/users')
.then(res=>res.json())
.then(data=>show(data))

function show(data){
 const cardsContainer = document.getElementById('cards-container');
 cardsContainer.innerHTML='';
 data.map(element => {
    const cardDiv = document.createElement('div')
    cardDiv.className= "col-md-4"
    cardDiv.innerHTML=`
    <div class='card p-5 m-1'>
        <h3>${element.name}</h3>
        <h5>${element.email}</h3>
        <button class="btn btn-primary" id='card-button' onclick='setLocalStorage(e)'>Add to Card</button>
    </div>
    `
    cardsContainer.appendChild(cardDiv);
});
}

function setLocalStorage(e){
 console.log("clicked",e)
}

I got this error in console https://d.pr/i/JCjI77

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

0

I've run into this issue a few times before as well.

First, I would suggest using jquery anyway. When writing plain html, I almost always use jquery. It makes interaction with the DOM much easier. So here is an example in jquery of the onClick event for an element with id="card-button". A normal click event won't work from jquery here. You have to set it on the document and then further set a selector:

fetch('https://jsonplaceholder.typicode.com/users')
.then(res=>res.json())
.then(data=>show(data))

function show(data){
 const cardsContainer = $('#cards-container');
 cardsContainer.html("");
 data.map(element => {
    cardsContainer.append(`
    <div class='card p-5 m-1 col-md-4'>
        <h3>${element.name}</h3>
        <h5>${element.email}</h3>
        <button class="btn btn-primary" id='card-button'>Add to Card</button>
    </div>
    `
});
}

$(document).on("click", "#card-button", function(e) {
    setLocalStorage(e)

    // or you can just place the contents of setLocalStorage directly 
    // into here! 
})

function setLocalStorage(e){
 console.log("clicked",e)
}

you can remove onClick from the button element here. Make sure you remember to import jquery. Ideally the minified version.

BUT YOU HAVE ANOTHER MORE IMPORTANT ISSUE

you're creating multiple add card buttons with the same id (card-button). you need to set card-button as a class. This way it can be applied multiple elements. I would suggest adding an ID to the button or cardDiv that is associated with userID, Index or any other unique identifier. This way you can recognize which user or card button is actually being pressed, and take action accordingly. Here is the updated jQuery with class instead of ID

fetch('https://jsonplaceholder.typicode.com/users')
.then(res=>res.json())
.then(data=>show(data))

function show(data){
 const cardsContainer = $('#cards-container');
 cardsContainer.html("");
 data.map(element => {
    cardsContainer.append(`
    <div class='card p-5 m-1 col-md-4'>
        <h3>${element.name}</h3>
        <h5>${element.email}</h3>
        <button class="btn btn-primary" class="card-button" id='some-unique-id'>Add to Card</button>
    </div>
    `
});
}

$(document).on("click", ".card-button", function(e) {
    setLocalStorage(e)

    // or you can just place the contents of setLocalStorage directly into here! 

    // Here you can grab the jquery object with $(this), or use the 
    // ID with e.target.id with the e.target.id, etc...
    clickedButton = $(this);
    clickedButtonID = e.target.id;
})

function setLocalStorage(e){
 console.log("clicked",e)
}

I don't use plain HTML without jQuery often, so I can't answer for sure if you want to take that route. It seems as if this previous thread answers that question, definitely better than I could.

unable to use getElementById on HTML element not yet appended to document

Best of luck!!

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!