suppose some markup such as:
<div id="header">
<div id="nest-one>
<a href="#">one</a>
<div id="nest-two">
<a href="#">two</a>
<a href="#">three</a>
</div>
</div>
</div>
and I want to tie a single click handler to all of the a tags.
I tried the following, but didn;t seem to work. I know I'm missing something stupid easy, just not sure what it is.
$('#header a').click(function(){alert('on click')});
suppose some markup such as:
<div id="header">
<div id="nest-one>
<a href="#">one</a>
<div id="nest-two">
<a href="#">two</a>
<a href="#">three</a>
</div>
</div>
</div>
and I want to tie a single click handler to all of the a tags.
I tried the following, but didn;t seem to work. I know I'm missing something stupid easy, just not sure what it is.
$('#header a').click(function(){alert('on click')});
Share
Improve this question
asked Aug 17, 2011 at 1:28
shsteimershsteimer
28.8k30 gold badges80 silver badges95 bronze badges
1
- 3 Is that line of JavaScript in the document ready, or at least after the HTML in the source? – nnnnnn Commented Aug 17, 2011 at 1:31
3 Answers
Reset to default 5On this line:
<div id="nest-one>
You've missed the closing double-quote on the id.
Aside from that, make sure any JavaScript referencing HTML elements is in the document ready function and/or after those elements in the source.
Demo
EDIT
per BoltClock's point:
This works actually
$('#header a').click(function(){alert('on click')});
Use $.live or $.delgate, this will also bind to any future elements added dynamically to the DOM.
example:
$("#header").delegate("a", "click", function() {
console.log("%o clicked", this ); // log object in firebug
});