0

I would like to click divs inside an #TAGS1

$(document).on('click','div > #TAGS1',function(){alert('go crazy');});

I tried a variety of things but I cannot seem to make it work. I would like to use .on.

2
  • Why .on() vs .click()? Are your divs added dynamically? Commented Apr 28, 2014 at 20:45
  • Yes they are added dynamically Commented Apr 28, 2014 at 20:47

6 Answers 6

3

Try:

$('#TAGS1 div').on('click',function(){alert('go crazy');});
Sign up to request clarification or add additional context in comments.

1 Comment

I need to use $(document) because in my case, TAGS1 is loaded onto the page. Without $(document) it will otherwise not pick up the new added TAGS1
1

You can try this

<script type="text/javascript">
    $(document).on('click','#TAGS1 > div',function(){
        alert('go crazy');
    });
</script>

<div id="TAGS1">
  <div>Text 1</div>
  <div>Text 2</div>
  <div>Text 3</div>
</div>

1 Comment

Perfect! I had it backwards. appreciate it
1

If you have an element with #TAGS1 and you want handle clicks on every div inside of that element than this should work for you.

FIDDLE

<section id="TAGS1">
    <span>span1</span>
    <div>div1</div>
     <div>div2</div>
      <span>span2</span>
</section>



 $(document).on('click','#TAGS1 div',function(){alert('go crazy');});

Comments

0
$("#TAGS1 div").click(function() {
    alert('go crazy');
});

Comments

0

The jquery method .click() is an shortcut to the click event for .on(), changing your event binding to:

$('#TAGS1 div').click(function(e){
  alert('go crazy');
});

Should achieve what you want.

If you really want to use .on() you can do so using the following:

$(document).on('click', '#TAGS1 div', function(e) {
  alert('go crazy');
});

Comments

-3

the hell?

provide your jquery version next time...

Anyways. your outdated code resembles this of updated and more preferred code.

$("div > #TAGS1").click(function(e){
     alert("clicked");
});

if your code is not working still, then you have an issue with your html. div > #tags1 is saying.. Tags1 is a child of division. make sure that is true in your html.

1 Comment

$("div > #TAGS1").click( will add a handler to all matching tags when that code runs, $(document).on('click','div > #TAGS1', will bind the click handler to document, and act only on elements matching div > #TAGS1. This is known as event delegation and as jQuery's docs put it: Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future. -1 for tone.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.