• Menu with Submenu" />
  • Menu with Submenu" />
  • Menu with Submenu"/>

    TechQA.

    jQuery, manipulate dynamically created element in callback of a click on it

    280 views Asked by bluantinoo At 2017-02-02T19:20:47+00:00 02 February 2017 at 19:20 2025-12-16T23:07:05+00:00

    I have a mobile menu with this (simplified) html

    <ul id="mobile_menu">
        <li class="menu-item menu-item-has-children">
            <a href="#">Menu with Submenu</a>
            <ul class="sub-menu">
                <li class="menu-item"><a href="#">Submenu item 1</a></li>
                <li class="menu-item"><a href="#">Submenu item 2</a></li>
                <li class="menu-item enu-item-has-children"><a href="#">Submenu item 3</a>
                    <ul class="sub-menu">
                        <li class="menu-item"><a href="#">Sub-Submenu item 1</a></li>
                        <li class="menu-item"><a href="#">Sub-Submenu item 2</a></li>
                    </ul>
                </li>
            </ul>
        </li>
        <li class="menu-item"><a href="#">menu item 2</a></li>
        <li class="menu-item"><a href="#">menu item 3</a></li>
    </ul>
    

    I create an helper element to close submenus in mobile devices. I create it in a function, like this:

    var mainli_a =  jQuery('#mobile_menu .menu-item-has-children > a');
    
    mainli_a.on('touchstart click', function(e){
    
                        "use strict";
                        var link = jQuery(this);
                        if (link.parent().hasClass('active')) {
                            return true;
                        } else {
                            link.parent().addClass('active')
                            link.parent().append('<span class="closesubmenu"> </span>');  // here I create the element
    
                            e.preventDefault();
                            return false; 
                        }
                    });
    

    The element I'm speaking about is the span.closesubmenu

    Then, on a click on it, i want to remove a class to its parent element, and then remove the element .closesubmenu itself.

    This is how i try:

       jQuery('body').on('touchstart click', 'span.closesubmenu', function(e){
    
                jQuery(this).parent().removeClass('active', 0, 'linear', function(){
                     jQuery(this).remove(); // this does not work
                });
    
        });
    

    It does not matter wich manipulation i try in the callback to closesubmenu. it does not work.

    It only work only like this:

     jQuery('body').on('touchstart click', 'span.closesubmenu', function(e){
    
             jQuery(this).remove(); // this works    
    
        });
    

    Furthermore, if I just put 2 manipulations on 2 lines, only the first one works:

     jQuery('body').on('touchstart click', 'span.closesubmenu', function(e){
    
             jQuery(this).remove(); // this works  
             jQuery(this).parent().removeClass('active'); // this does not work 
    
        });
    
     jQuery('body').on('touchstart click', 'span.closesubmenu', function(e){
    
             jQuery(this).parent().removeClass('active'); // this works  
             jQuery(this).remove(); // this does not work 
    
        });
    

    What am I missing here?

    UPDATE:

    I tried also as suggested in answers, to store the element in a var to use in the callback, like this:

                jQuery('body').on('touchstart click', 'span.closesubmenu', function(e){
                    var self = this;
                    jQuery(self).parent().removeClass('active', 0, 'linear', function(){
                        jQuery(self).remove();
                    });
            });
    

    But it is not working.

    UPDATE 2: jsFiddle

    https://jsfiddle.net/bluantinoo/yr4gdjdz/3/

    UPDATE 3: Thanks to David (chosen answer) this is the correct and working fiddle: https://jsfiddle.net/bluantinoo/yr4gdjdz/6/

    javascript jquery callback dynamically-generated removeclass
    Original Q&A
    1

    There are 1 answers

    8
    David David On 2017-02-02T19:26:17+00:00 02 February 2017 at 19:26 BEST ANSWER

    What are all these parameters you're passing to .removeClass()?

    jQuery(this).parent().removeClass('active', 0, 'linear', function(){
        jQuery(this).remove();
    });
    

    It's only expecting the class name(s). And it's not an asynchronous operation with a callback. Just remove the class(es) and then remove the element:

    jQuery(this).parent().removeClass('active');
    jQuery(this).remove();
    

    Example.

    Related Questions in JAVASCRIPT

    • Using Puppeteer to scrape a public API only when the data changes
    • inline SVG text (js)
    • An array of images and a for loop display the buttons. How to assign each button to open its own block by name?
    • Storing the preferred font-size in localStorage
    • Simple movie API request not showing up in the console log
    • Authenticate Flask rest API
    • Deploying sveltekit app with gunjs on vercel throws cannot find module './lib/text-encoding'
    • How to request administrator rights?
    • mp4 embedded videos within github pages website not loading
    • Scrimba tutorial was working, suddenly stopped even trying the default
    • In Datatables, start value resets to 0, when column sorting
    • How do I link two models in mongoose?
    • parameter values only being sent to certain columns in google sheet?
    • Run main several times of wasm in browser
    • Variable inside a Variable, not updating

    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 CALLBACK

    • TelephonyCallback.CallStateListener with LiveData and ViewModel
    • M-Pesa Daraja API STK Push Callback Not Triggering in Node.js Application
    • Qt: running callback in the main thread from the worker thread
    • Why am I getting MethodErrors when using continuous callback in Julia ODE solver?
    • In Rails 7, what is the right ActiveRecord callback to use if I need to prevent (or rollback) persistance on error?
    • How to get variable from GWT Callback
    • How to execute code "before_serialize"? or How can I sanitize attributes before they are serialized?
    • Is there a way to add a pre-hook in R?
    • Understanding use of closure in callback in javascript
    • How can I make firebase realtime dtabase to act as a webhook endpoint
    • How do you sort a list view in Visual C++?
    • Second useState doesn't update in promise chain
    • How to wait for one api call to complete before making another api call without using `await` in vue pinia store
    • Kotlin labmda invoke alternatve
    • Sveltekit on change function not being called when added to a component

    Related Questions in DYNAMICALLY-GENERATED

    • How to pass a Blazor Component Instance to other Component and render it?
    • Is there a way to create a c# Controller that provides a dynamically structured dataset as well as parameters?
    • How do I dynamically change nav link text color based on background brightness?
    • Python - Having trouble dynamically creating buttons with images
    • Warning: Expected server HTML to contain a matching <form> in <div>
    • How to specify the favicon image when generating it programmatically in Next.js
    • Dynamically creating objects in a vectorC++
    • How can I enable flex-wrap behavior on a dynamically generated row of bootstrap cards?
    • Woocommerce redirect dynamically after login
    • Is it possible to download image from website via Selenium (Python) in case is generated dynamically from server?
    • Angular2: Are dynamically created injectors (created via Injector.create(...)) ever destroyed?
    • Call function in a component created dynamically using ANGULAR
    • How to render child and grand child components both created dynamically
    • Issue with extracting data from javascript generated html doc
    • Android Studio ImageButton Tooltip has curious behavior if button is created in java source file

    Related Questions in REMOVECLASS

    • Adding and removing classes on mutiple divs
    • setTimeout() doesn't work with jQuery(this)
    • jQuery, manipulate dynamically created element in callback of a click on it
    • Toggle class using javascript between two
    • How to add and remove class when user clicks and hover a link
    • Attempt to removeClass in jquery fails
    • jQuery .click function not work after reload
    • Remove a class when two divs overlap
    • Uncaught TypeError: element.removeClass is not a function In Jquery
    • jQuery click function not working (addClass / removeClass)
    • removeClass is not working if href exist in anchor
    • changing the functionality of the toggle button in mobile view
    • Using link to remove list items from page using HTML5 and Javascript
    • jQuery removeClass and addClass not working
    • Having trouble removing from BST

    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?

    Popular Tags

    javascript python java c# php android html jquery c++ css ios sql mysql r reactjs node.js arrays c asp.net json

    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