• Trigger Me!
  • Trigger Me!
  • Trigger Me!
    " />
    • Trigger Me!
    • Trigger Me!
    • Trigger Me!
      " />
      • Trigger Me!
      • Trigger Me!
      • Trigger Me!
        "/>

        TechQA.

        jQuery Selector only on first level not working?

        295 views Asked by DominikAmon At 2014-01-24T14:17:38+00:00 24 January 2014 at 14:17 2025-12-21T22:37:49+00:00

        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 answers

        0
        gpgekko gpgekko On 2014-01-24T14:21:57+00:00 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 2014-01-24T14:32:08+00:00 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

        • In Datatables, start value resets to 0, when column sorting
        • Bootstrap modal not showing at the desired position on a web page when the screen size is smaller
        • window.location.href redirects but is causing problems on the webpage
        • Using JQuery Date Slider
        • Storing selected language in localStorage
        • How to stop other divs from still showing when i click a different button?
        • Check multiple values with jQuery
        • Bootstrap component does not want to render in Datatables function
        • put white spaces when entering an amount moneytype symfony
        • Trouble accessing custom header in AJAX response using jQuery in Fiware Keyrock
        • I just cant make it work, HTML, JS and Firebase error
        • Didn't declared variable still not getting any error in JavaScript
        • Move element horizontally while scrolling vertically in pure JavaScript
        • allow multi carousel in same page
        • Embedded TikTok posts / thumbnail styling issue

        Related Questions in JQUERY-SELECTORS

        • app.js:55 Uncaught TypeError: Cannot read properties of undefined (reading 'value')
        • Why does MutationObserver not detect nodes after a random point?
        • tinymce setContent and setMode Operation
        • In Javascript, how can I querySelector to get the innerHTML excluding one of the inner sibling divs
        • How can I press Tab key and Enter key on browser using browser's console?
        • "OR" in var selector
        • I would like to change the execution order of my event listeners but they are interdependent
        • Contains to return multiple values
        • What should be used instead of document.queryselectorAll() in React?
        • How can I select a DOM element, which name is changing
        • Can't get value from child element using JQuery
        • Iterate Form with queryselectorall to put input value into array
        • How to use Javascript to expand Google PAA section?
        • JavaScript Click does not work on Google translate image
        • 3cx change bubble button style in Wordpress functions.php - move up an async button and styling it after waiting fetch for async dom created

        Related Questions in JQUERY-TRIGGER

        • JQuery trigger click does not return target id
        • How do I simulate jquery events to trigger Google Autocomplete?
        • 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
        • Selecting all elements except for div not working with jQuery
        • jquery .click() does not work
        • Javascript bugs in event handling
        • Why does triggering a 'click' result in a different Event on radioButton and Checkbox?
        • jquery/javascript: $(document).trigger vs normal function call?
        • jQuery programatically click a tag that has javascript:void(0)
        • Passing parameters to $(window).on('resize') when using .trigger('resize')
        • Triggering click event on anchor tag doesn't work
        • transition of border when element size changes in jq
        • Passing global variable in javascript to live event on jquery does not work
        • jQuery trigger performance

        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?

        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)
        • Privacy
        • Terms
        • Cookies
        • Homegardensmart
        • Math
        • Aftereffectstemplates