0

I want a parent div to be clickable through using javascript. Here is the code:

document.getElementById("box").addEventListener("click", function() {
  window.location.href = "https://example.com";
});
#box {
  width: 200px;
  height: 200px;
  background-color: red;
}
<div id="box">
  //something
</div>

But the script doesn't work. I've replaced the script by the following one, but still doesn't work:

document.querySelector("#ID").addEventListener("click", function() {
  window.location.href = "https://example.com";
}); 

so, where am I doing wrong?

Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
  • 2
    In your second script: since your ID is `box` and not `ID`, you won't get any element returned by your selector. – CherryDT Sep 12 '21 at 13:34
  • 1
    But your first script works just fine, as you can see by clicking the "run code snippet" button in your question and clicking the box. It redirects to example.com for me. Can you please explain what the issue is? – CherryDT Sep 12 '21 at 13:35
  • (For clarification: It worked with your original code, even before Mister Jojo edited it.) – CherryDT Sep 12 '21 at 13:37
  • 1
    Try `document.addEventListener("DOMContentLoaded", function(e) { document.getElementById("box").addEventListener("click", function() { ... }); });` – icecub Sep 12 '21 at 13:37
  • Thank you all, and specifically you @CherryDT for mentioning me in the above topic . It hit the nail on the head. I just moved the scripts down the parent div in the DOM and the problem got solved! – Vanda Nojan - وندا نوژن Sep 12 '21 at 15:02

0 Answers0