• Trigger Me!
  • Trigger Me!
  • Trigger Me!
    " />
    • Trigger Me!
    • Trigger Me!
    • Trigger Me!
      " />
      • Trigger Me!
      • Trigger Me!
      • Trigger Me!
        "/>
        DEVHIDE
        • Home (current)
        • About
        • Contact
        • Cookie
        • Home (current)
        • About
        • Contact
        • Cookie
        • Disclaimer
        • Privacy
        • TOS
        Login Or Sign up

        jQuery Selector only on first level not working?

        291 Views Asked by DominikAmon At 24 January 2014 at 14:17 2025-12-10T13:44:03.117000

        I have a simple list with a sublist

        <div id="master">
        <ul>
            <li><div>Trigger Me!</div></li>
            <li><div>Trigger Me!</div></li>
            <li><div>Trigger Me!</div>
                <ul>
                    <li><div>Do NOT trigger me</div></li>
                    <li><div>Do NOT trigger me</div></li>
                </ul>
            </li>
        </ul>
        

        I'd only like to call a function only if the user clicks on the list element on the first level, but NOT on the second. Regarding to the documentation and google, the trick should be easy by using the ">" in the selector:

        $(document).ready(function(){
          $("div#master").on("click", "ul > li", function (){
            alert($(this).text());
          });
        });
        

        But as you can see on JSFiddle http://jsfiddle.net/kQH4x/ it also fires the trigger, when clicking on the sub list items.

        A simular problem with the answer on stackoverflow (See here https://stackoverflow.com/a/977891/1099519 ) doesn't seem to work for some reason?

        Thanks

        jquery jquery-selectors jquery-trigger
        Original Q&A
        2

        There are 2 best solutions below

        0
        gpgekko gpgekko On 24 January 2014 at 14:21 BEST ANSWER

        It also fires on the sublist because you don't specify which ul it should start from. The sublist has the same structure, so also qualifies for the selector.

        To fix this, add the main lists parent element to the selector, so:

        $(document).ready(function(){
           $("div#master").on("click", ">ul>li>div", function (){
              alert($(this).text());
           });
        });
        

        Fiddle: http://jsfiddle.net/kQH4x/6/

        1
        beck03076 beck03076 On 24 January 2014 at 14:32

        Try this,

        • Don't have to use (document).ready every time.
        • Why "on", just bind "click" and read when to use "on" here
          $(function(){
               $("div#master > ul>li>div").click(function (){
                  alert($(this).text());
               });
            });
        

        Related Questions in JQUERY

        • How to sort these using Javascript or Jquery Most effectively
        • Ajax jQuery firing multiple time display event for the same result
        • .hover() seems to overwrite .click()
        • Check for numeric value with optional commas javascript
        • Extending Highmaps Side Effect
        • Array appending after each onclick and loop in javascript
        • how can i append part of a table based on how many tr it has?
        • Play multiple audio files in a slider
        • Remove added set of rows
        • Access property of an object of type [Model] in JQuery
        • AJAX PHP - Reload div after submit
        • proengsoft/laravel-jsvalidation ReferenceError: jQuery is not defined
        • when a checkbox is checked how to display a different hidden element using javascript
        • Get jquery error Uncaught RangeError: Maximum call stack size exceeded
        • Removing only the closest thead on table filtering

        Related Questions in JQUERY-SELECTORS

        • Click Event Not Working After Class Change
        • JQuery .find() failing on an .ajax() result
        • How can I implement a plugin on element with exception of inner element
        • jQuery button to show/hide multiple divs with same id
        • How to get the Value of an ID from a TR of a Clicked TD Element
        • What is faster/more efficient - $(".selector").height() vs $(".selector").eq(0).height()
        • Why does jQuery's :contains count unexpected in my code?
        • Jquery Change CSS of variable div
        • Remove empty <p>, but allow only one per group
        • How to check if TD is last with class in row
        • Style first and last element for each
        • Jquery Multiple Attribute Selector not working
        • Difference between "+" and "~"
        • Using string variables within a jquery selector
        • Select element with same class and other class

        Related Questions in JQUERY-TRIGGER

        • jQuery programatically click a tag that has javascript:void(0)
        • Manually set combobox's value doesnt work before triggering change event
        • Simulate javascript to choose from dropdown
        • Fill Combo on change Trigger using JQuery
        • How do I simulate jquery events to trigger Google Autocomplete?
        • "Out" event in a sortable is never triggered
        • jQuery Selector only on first level not working?
        • JQuery trigger click does not return target id
        • Javascript bugs in event handling
        • Why is .trigger() not working when a selector is added to .on()?
        • How can I pass a parameter/argument to the onchange listener that is programmatically triggered by a call to click
        • Need to pass specific JQueryEventObject AND parameters to trigger
        • How can I put parametres into JQuery.Event data property and trigger it?
        • Selecting all elements except for div not working with jQuery
        • jquery triggerHandler doesn't work while trigger does

        Trending Questions

        • UIImageView Frame Doesn't Reflect Constraints
        • Is it possible to use adb commands to click on a view by finding its ID?
        • How to create a new web character symbol recognizable by html/javascript?
        • Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
        • Heap Gives Page Fault
        • Connect ffmpeg to Visual Studio 2008
        • Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
        • How to avoid default initialization of objects in std::vector?
        • second argument of the command line arguments in a format other than char** argv or char* argv[]
        • How to improve efficiency of algorithm which generates next lexicographic permutation?
        • Navigating to the another actvity app getting crash in android
        • How to read the particular message format in android and store in sqlite database?
        • Resetting inventory status after order is cancelled
        • Efficiently compute powers of X in SSE/AVX
        • Insert into an external database using ajax and php : POST 500 (Internal Server Error)

        Popular # Hahtags

        javascript python java c# php android html jquery c++ css ios sql mysql r reactjs

        Popular Questions

        • How do I undo the most recent local commits in Git?
        • How can I remove a specific item from an array in JavaScript?
        • How do I delete a Git branch locally and remotely?
        • Find all files containing a specific text (string) on Linux?
        • How do I revert a Git repository to a previous commit?
        • How do I create an HTML button that acts like a link?
        • How do I check out a remote Git branch?
        • How do I force "git pull" to overwrite local files?
        • How do I list all files of a directory?
        • How to check whether a string contains a substring in JavaScript?
        • How do I redirect to another webpage?
        • How can I iterate over rows in a Pandas DataFrame?
        • How do I convert a String to an int in Java?
        • Does Python have a string 'contains' substring method?
        • How do I check if a string contains a specific word?

        Copyright © 2021 Jogjafile Inc.

        • Disclaimer
        • Privacy
        • TOS
        • Homegardensmart
        • Math
        • Aftereffectstemplates