With JQuery ( light weight, super Java Script library) we can handle events, dynamically add content to html blocks. Let’s learn how to add content to div using class id/class
jQuery
jQuery can be placed in a file or with in HTML , I used to store them as file for easy access. It is a good practice include it in a document ready function, so that we can make sure the query will only execute only when the web page loading completed.
$(function () { // code block here }
HTML
In the HTML file very last line of the body (</body>) tag include the script as follows, also you need to include the CDN version or local version of jQuery library.
<script src="/jquery.js"></script> -- local version of jQuery library <script src="/public/script.js"></script> -- our script
Adding the content
Adding the content to a div can be achieved
- access the DOM element using id
- Placing content using one of the following method
append()
– Inserts content at the end of the selected elementsprepend()
– Inserts content at the beginning of the selected elementsafter()
– Inserts content after the selected elementsbefore()
– Inserts content before the selected elements
Here is the plan
- Find the element using jQery function
- Clear the content
- Append the content
$(function () { var divEl=$("#content-area") divEl.htm('') divEl.appen('<p>I am a paragraph</p>') });
Here the divEl.html(”) is used to clear the content. We can also use class to access the element in a HTML file by using $(‘className’)
I recommend the following post for further read
- How to add data on MongoDB using Node-Express API
- POST API Call using jQuery and AJAX
- GET API Call using jQuery and AJAX
- How to create animated tool tip container with CSS and jQuery
- How to add/remove CSS class using jQuery
- How to show/hide DOM element using jQuery
- How to redirect a page in jQuery
- How to load content into div using jQuery
- How to refresh / reload content to a div using jQuery