This is a pattern that I have seen used in a few projects and think it is good for when you need the same menu in 2 places. This is quite common when you have a desktop navigation and need a second copy for a mobile pop-out menu.
How to Copy an HTML Element to another div
const $mobile_nav = $("#mobile-nav"); const $main_nav = $("#block-spamenu").html(); $mobile_nav.append($main_nav);
As you can see the script is simple.
- First, you select the div for the mobile navigation, this needs to be added to the HTML.
- Then copy the menu element with the .html() method.
- Finally, append the HTML to the element created in step 1.
In the below script, we use the innerHTML property to copy code and insertAdjacentHTML in place of append. Other than these differences, jQuery has the $ shorthand for selecting elements In place of the $ we use getElementByID but we could use any of the Instance methods available to select elements in the document object model.
const mainNavDesktop = document.getElementById("desktop-nav"); const mainNav = document.getElementById("block-spamenu").innerHTML; mainNavDesktop.insertAdjacentHTML( "afterbegin", mainNav);
As such this is a whole other article but you will notice this instance method takes the position and a string that is parsed as HTML or XML. The position,
afterbegin in this script, is handy as in jQuery you have other methods to achieve the same.
I know this will be controversial to some, but hey, I am not saying to learn jQuery or even use it. Just become familiar with it as it is still widely used and it may open many more opportunities for you.
Thanks for reading and till next time, seize the day!