How Jquery Can be Used to Add and Position Elements

Sometimes HTML and CSS is not the fastest way to achieve your aim.  Take for example a site I was working on last week, where I was restricted in modifying the source html pages,  and manipulating elements with absolute CSS positioning was going to be a headache for mobile responsive views.

The objective:  I wanted to add a button to a specific position on the page to view all categories within the an eCommerce site.

With jquery you can navigate the DOM and elements within the DOM (Domain Object Model), and add, append data to a page easily.

The solution: The following jquery finds the class element .homePageCategories .listWrapper within the page, and adds the html code for the button directly after it.

<script>$( “.homePageCategories .listWrapper” ).after( “<a class=’allcategoriesbtn’ href=’/test/c/15/all-categories’ title=’Show products in category All Categories’>All Categories</a>” );</script>

The image below shows the ‘ALl CATEGORIES’ button positioned after the div.listwrapper element (which is highlighted).  View the inspect element window below for a view of the html/CSS,  where you can see the two classes referenced; .homePageCategories and  .listWrapper

There are many more jquery commands that can be used like append, find, before…plus many more.
















If you are looking for a short, informative free course on Jquery, take a look at codeschool’s jquery course here.