varun teja
varun teja

Reputation: 336

querySelectorAll not working?

this is my javascript code:

function answer(){
var list = document.querySelectorAll("#fish");
list[1].onclick = talk();
}

function talk(){
alert('hello!');
}

window.onload = answer();

on run it pops my browser window with alert: 'hello'. my html code:

<!DOCTYPE html>
<html>
<head>
<title>my site</title>
<script src="new 3x.js"></script>
</head>
<body>
<section>
<p id="fish">hello world!</P>
<p id="fish">tuna</P>
<p id="stuff">durr</P>
</section>
</body>
</html>

it alerts hello on loading the tab.whereas i want it to run alert when i click tuna!

Upvotes: 0

Views: 3863

Answers (2)

Erik Terwan
Erik Terwan

Reputation: 2780

If you are using IDs why use querySelectorAll in the first place? Just use getElementById.

var list = document.getElementById("fish");
list.addEventListener('click', talk, false);

EDIT

Now i see you are using non-unique IDs, what in my opinion is bad practice. Why not just use the class fish ?

<p class="fish">hello world!</P>
<p class="fish">tuna</P>
<p id="stuff">durr</P>

Then select like so:

var list = document.querySelectorAll(".fish");
list[0].addEventListener('click', talk, false);

Upvotes: 0

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239814

You're not assigning event handlers correctly - you're assigning the result of invoking your functions, rather than the functions themselves. Remove the ()s:

function answer(){
var list = document.querySelectorAll("#fish");
list[1].onclick = talk;
}

function talk(){
alert('hello!');
}

window.onload = answer;

What's currently happening is that, as soon as the window.onload = answer(); line is hit, you're immediately running the answer function. It, in turn when it reaches the onclick line, is immediately invoking the talk function. That's not what you wanted.

Upvotes: 1

Related Questions