Modify HTML with jQuery

This post is a short brief about some basic jQuery, such as creating ans inserting HTML elements, moving HTML element in DOM, removing HTML elements. It is also about adding and removing classes, modifying styles and HTML content.

Creating HTML element

$h1 = $('<h1>I am a new header</h1>');

Inserting HTML element

.prepend() inserts the specified element as the first child of the target element.

.append() inserts the specified element as the last child of the target element.

.appendTo() does the same as .append(), but it just reverses the order of "what to add" and "where to add it.

You can specify where in the DOM you insert html element (or more elements) with the .before() and .after() methods:

$('element').after('some html code');

if you want to insert more html elements, you are not allowed to use line breaks in the parameter string of after() (so you have to delete line breaks).

Moving HTML element

You can move an existing element with the help of after() method:

$('target element').after($('moving element'));

Removing HTML element

.empty() deletes an element's content and all its descendants.

.remove() not only deletes an element's content, but deletes the element itself.

Some list

<p><strong>Some list</strong></p>
<ul id="someList">
</ul>
<div>
    <button class="addItem">Add item</button>
    <button class="remItem">Remove item</button>
</div>

<script>    
$(function(){
    var counter = 0;
    $('button.addItem').click(function() {
        counter++;
        itemStr = '<li id=li'+ counter.toString() +'>' + counter.toString() + '. item</li>'
        $('#someList').append(itemStr);         
    });
    $('button.remItem').click(function() {        
        if (counter > 0) {
            $('#li'+counter.toString()).remove(); 
            counter--;
        }
        else {
            alert("The list is empty");
        }        
    });
});
</script>

You can remove an element (and its descendants) by clicking it like this:

$(document).on('click','selector', function(){
    $(this).remove();
});

Adding and removing classes

.addClass() and .removeClass() can be used to add or remove a class from an element.

Modifying Style

You can modify an element's style with css method:

$('element').css('property', 'value');

Modifying HTML content

You can update the contents of HTML elements using the .html() and .val() functions.

.html() can be used to get/set the contents of the first element match it finds. For example to get contents of an element:

$p_variable = $('p').html();

.val() is used to get/set the value of form elements.


Sources

(1) Codecademy

(2) w3Schools


comments powered by Disqus