With jQuery you can add and remove HTML elements on a page, and modify their content.

Adding New Elements

There are two ways to add new elements in a web page, you can create the element and then insert it in the page to a specific location, or you can directly add the HTML item in the page.

1. Creating an HTML item and then insert it

To create new HTML tag, use this syntax:
$('<tag>New Content</tag>');
jQuery parses the HTML into a DOM fragment and selects it, just as an ordinary jQuery selector does. That means it's instantly ready for further jQuery processing.

To add a class to the new element, use this syntax:
$('<tag>New Content</tag>').addClass('class_name');

Once the new element is created, you can insert it in the page where we'd like it to go. There are several jQuery functions available for this purpose.

    newItem.insertAfter(target)   - inserts the newItem. into the page after the specified target.
    newItem.insertBefore(target)   - inserts the newItem. into the page before the specified target.
    newItem.appendTo(target)   - adds the newItem as a child of the "target" (appears inside the "target"), at the end, after all other existing children.
    newItem.prependTo(target)   - adds the newItem as a child of the "target" (appears inside the "target"), at the beginning, before other existing children.
- "target" can be a selector that represents a single element or a set of items, in this case the "newItem" will be added to all set of elements.

Example:
<style type="text/css"><!--
.spn { color:blue; font-weight:bold; }
--></style>
<script type="text/javascript"><!--
$(document).ready(function() {
  var new_btn = $('<button id="btn">Click</button>');          // new button
  var new_span = $('<span>START</span>').addClass('spn');      // new <span> with class="spn"

  new_btn.insertAfter('#idd');        // insert the new button after the tag with id="idd"

  // now we use the new added button, when is clicked
  $('#btn').click(function() {
    // insert the "new_span" at the beginning inside all DIVs with class="cls"
    new_span.prependTo('div.cls');
  });
});
--></script>

<div class="cls"> Create and insert new HTML items with jQuery</div>
<div class="cls" id="idd"> coursesweb.net</div>
The code above creates a <button> and a <span> tag to which adds a CSS class, inserts the button into the page, then uses it to register a click event that will add the <span> inside all <div> tags with class="cls", when the new button is clicked.
The button is inserted into our page after the "#idd", just as if we’d put it there in our HTML file. The new <span> with class="spn" receives the CSS properties set for this class.
Here's the result, click on the button:
Create and insert new HTML items with jQuery
coursesweb.net

- To add a specific attribute (like id, input, src) with jQuery, use this syntax:
Element.attr('attributeName', 'value');

2. Adding new HTML items directly to the target

There are several jQuery functions for adding HTML content directly to an existing element:

    $('selector').after('<tag>New content</tag>')   - inserts the new content into the page after the "selector".
    $('selector').before('<tag>New content</tag>')   - inserts the new content into the page before the "selector".
    $('selector').append('<tag>New content</tag>')   - adds the new content as a child of the "selector" (appears inside it), at the end, after all other existing children.
    $('selector').prepend('<tag>New content</tag>')   - adds the new content as a child of the "selector" (appears inside it), at the beginning, before other existing children.
- "selector" can be a single element or a set of items, in this case the New Content will be added to all of that set of elements.

In the following example we create an effect similat with the first example, but this time we use the functions presented above, and the <span> is added at the end (with append()):
<style type="text/css"><!--
.spn { color:blue; font-weight:bold; }
--></style>
<script type="text/javascript"><!--
$(document).ready(function() {
  $('#idd').after('<button id="btn">Click</button>');       // insert the new button after the tag with id="idd"

  // now we use the new added button, when is clicked
  $('#btn').click(function() {
    // insert a SPAN tag with class="spn" at the end in all DIVs with class="cls"
    $('div.cls').append('<span class="spn">END.</span>');
  });
});
--></script>

<div class="cls">Adding directly new HTML items with jQuery </div>
<div class="cls" id="idd">coursesweb.net </div>
As you can notice, this time the class="spn" is directly included in the tag, without using addClass() method.
To see the result, click on the button below:
Adding directly new HTML items with jQuery
coursesweb.net

Removing Existing Elements

To remove elements in jQuery, you first select them (as usual) with a selector, and then call the remove() method.
Syntax:
$('selector').remove('select');
- "select" - is an optional parameter that can be used to specify what to remove.
For example:   $('p.cls').remove();   removes all paragraphs with class="cls", the same with   $('p').remove('.cls');.
The remove action will remove all of the selected elements from the DOM, and will also remove any event handlers or data attached to those elements.

Example:
<script type="text/javascript"><!--
$(document).ready(function() {
  // when the tag with id="btn" is clicked
  $('#btn').click(function() {
    // removes all LI with class="cls" in OL
    $('ol li.cls').remove();
  });
});
--></script>

<ol>
 <li class="cls">List with class="cls".</li>
 <li>List without class.</li>
 <li class="cls">Another List with class="cls".</li>
</ol>
<button id="btn">Remove</button>
Click the "Remove" button to see the result (will delete all <li> tags with class="cls" in <ol>).
  1. List with class="cls".
  2. List without class.
  3. Another List with class="cls".

Read and Modifying Content

To get the HTML content of any item (similar to innerHTML in JavaScript), use this syntax:
$('Element').html();

To get only the text content, without HTML tags, use:
$('Element').text();

• Using similar syntax, but with a parameter for html() and text(), you can change the HTML or text content of a specified element.
To change the HTML content of any item, use this syntax:
$('Element').html('<tag>New Content</tag>');

To modify /replace with a text, use:
$('Element').text('New text content');

To understand the differences between text() and html(), try this example:
<script type="text/javascript"><!--
$(document).ready(function() {
  // when the tag with id="btn" is clicked
  $('#btn').click(function() {
    // gets the content of "#div1", with html(), and text()
    var dv_html = $('#div1').html();
    var dv_text = $('#div1').text();

    // displays the values in an alert window
    alert('html - '+ dv_html+ '\n text - '+ dv_text);

    // modify the content in "#div1" and "#div2"
    $('#div1').html('New content, changed with <u>html()</u>');
    $('#div2').text('New content, modified with <u>text()</u>');
  });
});
--></script>

<div id="div1">div1 <b>content</b>.</div>
<div id="div2">Another <u>HTML content</u></div>
<button id="btn">Click</button>
As you can notice, if you click the button bellow, when you get a content with text(), it removes the tags. When you add a HTML, the element will contain and display the entire content string exactly as defined, including the <tags>.
div1 content.
Another HTML content

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is used in <table> to create table header cell?
<thead> <th> <td>
<table><tr>
  <th>Title 1</th>
  <th>Title 2</th>
</tr></table>
Which CSS property sets the distance between lines?
line-height word-spacing margin
.some_class {
  line-height: 150%;
}
Which function opens a new browser window.
alert() confirm() open()
document.getElementById("id_button").onclick = function(){
  window.open("http://coursesweb.net/");
}
Indicate the PHP function that returns an array with names of the files and folders inside a directory.
mkdir() scandir() readdir()
$ar_dir = scandir("dir_name");
var_export($ar_dir);
Add and Remove HTML elements and Content with jQuery

Last accessed pages

  1. Countdown Timer with starting time added into a form - V.2 (823)
  2. Countdown Timer with starting time added into a form (6037)
  3. Sonic (1590)
  4. Heart shape with CSS (1635)
  5. innerHTML and outerHTML to Get and Replace HTML content (15094)

Popular pages this month

  1. Qwop (2996)
  2. Get Attribute (ID, Class, Name, Title, Src) with jQuery (2372)
  3. Get the value of the selected /checked checkboxes in a form (1497)
  4. Insert, Select and Update NULL value in MySQL (1339)
  5. Add, Change, and Remove Attributes with jQuery (1225)