Jquery Course

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 defines the clickable areas inside the image map?
<map> <img> <area>
<img src="image.jpg" usemap="#map1">
<map name="map1">
  <area shape="rect" coords="9, 120, 56, 149" href="#">
  <area shape="rect" coords="100, 200, 156, 249" href="#">
</map>
Which CSS property defines what is done if the content in a box is too big for its defined space?
display overflow position
#id {
  overflow: auto;
}
Click on the event which is triggered when the mouse is positioned over an object.
onclick onmouseover onmouseout
document.getElementById("id").onmouseover = function(){
  document.write("Have Good Life");
}
Indicate the PHP variable that contains data added in URL address after the "?" character.
$_SESSION $_GET $_POST
if(isset($_GET["id"])) {
  echo $_GET["id"];
}
Add and Remove HTML elements and Content with jQuery

Last accessed pages

  1. Prevent Hotlinking / Block External Access to Video and Audio files (4304)
  2. Check if table exists in database (9908)
  3. JavaScript trim, rtrim and ltrim (13011)
  4. Simple arithmetic calculator in PHP (2068)
  5. Select in two MySQL tables (5326)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (322)
  2. PHP Unzipper - Extract Zip, Rar Archives (112)
  3. Read Excel file data in PHP - PhpExcelReader (103)
  4. SHA1 Encrypt data in JavaScript (82)
  5. Get and Modify content of an Iframe (75)