1

I am using Magento 2, in my case I want to add an element after another using jQuery, can anyway tell me how to it, the best practice please

For example i want to insert a div with class 'one' after another div with class 'two'

$(".one").insertAfter(".two");

thank you in advance !

2

1 Answer 1

1

To use jQuery in Magento you need to add require before using jQuery, like this:

<script>
    require([
        'jquery'
    ], function($){
        $( "<div class='one'>Test</div>" ).insertAfter( ".inner" );
    });
</script>

Here is the detail of how insertAfter works is here: https://api.jquery.com/insertafter/

#Edited

If you want to do it in js level, then you don't need require you can use this criteria to add your js.

Add your js file in app/code/Vendor/Module/view/frontend/web/js/your_js_file.js

then add requirejs-config.js in app/code/Vendor/Module/view/frontend/requirejs-config.js

content of requirejs-config.js will be:

var config = {
paths: {
    'myfile': 'Vendor_Module/js/your_js_file'
},
 shim: {
    'myfile': {
        deps: ['jquery']
    },
}
};

Now you can use any jQuery functions in your file without using require

4
  • can i do this by creating a folder js to declare it into the file .js ?
    – coding mv
    Dec 20, 2020 at 14:11
  • Yes you can do this Dec 20, 2020 at 15:33
  • can you update your answer plz to see how
    – coding mv
    Dec 20, 2020 at 17:54
  • see updated answer Dec 21, 2020 at 6:13

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.