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 !

Shoaib Munir
9,59210 gold badges54 silver badges109 bronze badges
asked Dec 19, 2020 at 2:00
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

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.