jQuery adding and removing html elements | Lessoncup Programming Blog

Monday, 28 October 2013

jQuery adding and removing html elements

HI, today we are going to learn about adding and removing elements it could be html tags or it could be content inside the tags from cross browser, we can easily insert, replace, and remove the html elements from document.


To insert the new Elements

Appending
is a method to creating and inserting a new elements in a ending of specified element, the jQuery provides a .append() method to insert the new element right before the closing tag, the bellow example insert the DIV in document.

$('body').append('<div>');

To insert the new Elements with some text

the bellow code done the same thing, it will insert the text with in  <div> element inside the body tag.

$('body').append('<div>this is my text</div>');

To insert the new Elements to the beginning

Prepending is a method to creating and inserting a new elements in a beginning of a specified element, the jQuery provides a .prepend() method to insert the new element just before the starting tag, the bellow example insert the DIV in document.

$('body').prepend('<div>');

the above both examples it inserted only html/text at the beginning/ending of the selected html elements, we have two more methods and they give same output as we done with .append() and .prepend() methods,

those are .after() and .before() methods

the .after() method add the elements after the selected element

$('img').after('<div>text after image</div>');

the .before() method add the elements before the selected element

$('img').before('<div>text before image</div>');


To remove the Elements

Remove
 is a method to remove the elements from document, the bellow code removes the div from document.

$('.div').remove();

No comments :

Post a Comment

Mohammad Khasim
Blogger | Web Developer
Hyderabad - INDIA
lessoncup@gmail.com

PHP | My SQL | JQUERY
Web Development Tools | CMS | Frameworks | SEO

Get my Latest Lessons