DOM manipulation


Selectors


The three main types of selectors in jQuery are:

  1. Tag selectors: $('tagname')
  2. Class selectors: $('.classname')
  3. Id selectors: $('#idname')

Note: For more information on selectors please visit this link.

HTML

<!DOCTYPE html>
<html>
  <head>
    <meta charset='utf-8'>
    <title>Basic JQuery</title>
  </head>
  <body>
    <div id='list-wrapper'>
      <ul class='name-list'>
        <li>Marios</li>
        <li>Katerina</li>
        <li>Savvas</li>
      </ul>
    </div>
  </body>
</html>

The following scripts are included just before the closing body tag:

jQuery

<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script>
  // Id selector
  $('#list-wrapper').css('border', '3px solid red');

  // Class selector
  $('.name-list').css('background', 'green');

  // Tag selector
  $('li').css('color', 'blue');
</script>

Result

DOM traversal


jQuery provides a variety of methods that allow us to traverse the DOM. Most traversal methods are tree-traversal and that make sense since the DOM is a tree-like representation of the document. With traversal methods we can move up, down or sideways, visiting ancestors, descendants and siblings.

HTML

<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'>
        <title>Basic JQuery</title>
    </head>
    <body>
        <div id='Marios'>
            Marios
            <div id='Ioanna'>
                ----Ioanna
                <div id='Konstantina'>
                    --------Konstantina
                    <div id='Antreas'>
                        ------------Antreas
                        <div id='Neofitos'>
                            ----------------Neofitos
                            <div id='Georgia'>
                                --------------------Georgia
                                <div id='Lakis'>
                                    ------------------------Lakis
                                </div>
                                <div id='Alekos'>
                                    ------------------------Alekos
                                </div>
                            </div>
                            <div id='Sotiris'>
                                --------------------Sotiris
                                <div id='Athos'>
                                    ------------------------Athos
                                </div>
                            </div>
                        </div>
                        <div id='Eleni'>
                            ----------------Eleni
                        </div>
                    </div>
                    <div id='Giannis'>
                        ------------Giannis
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>

Result

CSS

.cyan::first-line {
    color: cyan;
}

.red::first-line {
    color: red;
}

.purple::first-line {
    color: purple;
}

.green::first-line {
    color: green;
}

.yellow::first-line {
    color: yellow;
}

The following scripts are included just before the closing body tag:

jQuery

<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script>
    // Immediate ancestor
    var ancestor = $('#Antreas').parent();
    ancestor.addClass('cyan');

    // Ancestors (Use 'div' to filter out the <body>)
    var ancestors = $('#Konstantina').parents('div');
    ancestors.addClass('red');

    // Immediate descendants
    var immediateDesc = $('#Antreas').children();
    immediateDesc.addClass('purple');

    // Descendants (Unlike the other methods the parameter for the
    // find() method is mandatory)
    var descendants = $('#Neofitos').find('*');
    descendants.addClass('green');

    // Siblings
    var siblings = $('#Antreas').siblings();
    siblings.addClass('yellow');
</script>

Result

Note: For more information on traversal methods please visit this link.

Toggling classes


API methods being used:

.addClass(className)
Add the specified class(es) to each element in the set of matched elements.
.addClass(function)
Add the specified class(es) to each element in the set of matched elements.
.toggleClass(className)
Add or remove one or more classes from each element in the set of matched elements.
.next([selector])
Get the immediately following sibling of each element in the set of matched elements.

Note: Mind that parameters inside [] are optional.

HTML

<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'>
        <title>Basic JQuery</title>
        <link rel='stylesheet' href='style.css'>
    </head>
    <body>
        <div id='example-1'>
            <strong>Example 1</strong>
        </div>
        <br>
        <div id='example-2'>
            <strong>Example 2</strong>
        </div>
        <br>
        <div id='example-3' class='yellow-bg'>
            <strong>Example 3</strong>
        </div>
        <br>
        <div id='example-4'>
            <strong>Example 4</strong>
        </div>
        <br>
        <div id='example-5.1' class='lime-border'>
            <strong>Example 5.1</strong>
        </div>
        <div id='example-5.2'>
            <strong>Example 5.2</strong>
        </div>
    </body>
</html>

Result

The following scripts are included just before the closing body tag:

jQuery

<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script>
    // Example 1: Add 'red-border' class to div#example-1
    $('#example-1').addClass('red-border');

    // Example 2: Add 'green-border' & 'blue-bg' classes to
    // div#example-2
    function myFunct1() {
        var cssClass = 'green-border blue-bg';
        return cssClass;
    }
    $('#example-2').addClass(myFunct1);

    // Example 3: Toggle (remove) 'yellow-bg' class from
    // div#example-3 & add an 'orange-border' class
    var example3 = $('.yellow-bg');
    example3.toggleClass('yellow-bg');
    example3.addClass('orange-border');

    // Example 4: Toggle (add) 'purple-bg' class to div#example-4
    $('#example-4').toggleClass('purple-bg');

    // Example 5: Toggle (remove) 'lime-border' class from
    // div#example-5.1 & add it to div#example-5.2
    var example5_1 = $('.lime-border');
    example5_1.toggleClass('lime-border');
    var example5_2 = example5_1.next();
    example5_2.toggleClass('lime-border');
</script>

Result

Note: For more methods please visit the jQuery API at this link.

Changing attributes


API methods being used:

.attr(attributeName)
Get the value of an attribute for the first element in the set of matched elements.
.attr(attributeName, value)
Set one or more attributes for the set of matched elements.
.first()
Reduce the set of matched elements to the first in the set.
.find(selector)
Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

HTML

<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'>
        <title>Basic JQuery</title>
    </head>
    <body>
        <ul>
            <li><a>Microsoft</a></li>
            <li><a href='https://www.apple.com/'>Apple</a></li>
            <li><a href='https://www.amazon.com/'>Amazon</a></li>
            <li><a href='https://abc.xyz/'>Alphabet</a></li>
            <li><a href='https://www.ibm.com'>IBM</a></li>
        </ul>
    </body>
</html>

Result

Here, we can use jQuery to add an href attribute to the a tag of the first item in the list. The following scripts are included just before the closing body tag:

jQuery

<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script>
    // Select the list items
    var items = $('ul li');
    // Select the first list item
    var firstItem = items.first();
    // Select the link
    var link = firstItem.find('a');
    // Add 'href' attribute
    $(link).attr('href', 'https://www.microsoft.com');
</script>

Result

Note: For more methods please visit the jQuery API at this link.

Modifying CSS


API methods being used:

.css(propertyName)
Get the computed style properties for the first element in the set of matched elements.
.css(propertyName, value)
Set one or more CSS properties for the set of matched elements by modifying the element's 'style' property.

HTML

<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'>
        <title>Basic JQuery</title>
    </head>
    <body>
        <h1 id='heading'>HELLO WORLD</h1>
    </body>
</html>

Result

Here, we can use jQuery to style the heading. The following scripts are included just before the closing body tag:

jQuery

<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script>
    // Select heading
    var heading = $('#heading');
    // Apply a single style
    heading.css('color', '#007f7f');
    // Apply multiple styles
    heading.css({'text-decoration':'overline', 'text-shadow':'-2px 0 #333'});
</script>

Result

Note: For more methods please visit the jQuery API at this link.

Pulling HTML/Text


API methods being used:

.html()
Get the HTML contents of the first element in the set of matched elements.
.text()
Get the combined text contents of each element in the set of matched elements, including their descendants.

HTML

<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'>
        <title>Basic jQuery</title>
    </head>
    <body>
        <div id='wrapper'>
            <h3>Largest car manufacturers (2016)</h3>
            <ul>
                <li>Toyota</li>
                <li>Volkswagen</li>
                <li>Hyundai/Kia</li>
                <li>General Motors</li>
            </ul>
        </div>
    </body>
</html>

Result

jQuery

var htmlContents = $('#wrapper').html();
console.log(htmlContents);
/* Output:

<h3>Largest car manufacturers (2016)</h3>
<ul>
    <li>Toyota</li>
    <li>Volkswagen</li>
    <li>Hyundai/Kia</li>
    <li>General Motors</li>
</ul>
*/

var htmlText = $('#wrapper').text();
console.log(htmlText);
/* Output:

Largest car manufacturers (2016)

    Toyota
    Volkswagen
    Hyundai/Kia
    General Motors
*/

Note: For more methods please visit the jQuery API at this link.

Collecting values


API methods being used:

.text(text)
Set the content of each element in the set of matched elements to the specified text.
.change(handler)
Bind an event handler to the 'change' JavaScript event, or trigger that event on an element. The change event is sent to an element when its value changes. This event is limited to <input>, <select>, and <textarea>. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for other element types such as input fields, the event is postpone until the element loses focus.
on('change', handler)
Bind an event handler to the 'change' JavaScript event, or trigger that event on an element. The change event is sent to an element when its value changes. This event is limited to <input>, <select>, and <textarea>. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for other element types such as input fields, the event is postpone until the element loses focus.
.val()
Get the current value of the first element in the set of matched elements. Primarily used to get the values of form elements such as <input>, <select> and <textarea>.

Note: Mind that .change(handler) is equivalent to .on('change', handler)

HTML

<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'>
        <title>Basic jQuery</title>
    </head>
    <body>
        <p>
            Write something in the input field below, and then click
            outside the field.
        </p>
        <form>
            Custom Header Text:
            <input id='input' type='text'>
        </form>
        <h1 style='color:#007f7f;text-shadow:-2px 0 #333;' id='live-header'>
            Default Text
        </h1>
    </body>
</html>

We'll add an event listener that will run any time the input changes. The event handler will get the value from the input field and use it to set the header content. The following scripts are included just before the closing body tag:

jQuery

<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script>
    $('#input').change(function() {
        var val;
        // Get the curent value of <input> element
        val = $('#input').val();
        // Set the content of <h3> element
        $('#live-header').text(val);
    });
</script>

Result

Note: For more methods please visit the jQuery API at this link.

Removing DOM elements


API methods being used:

.remove([selector])
Remove the set of matched elements from the DOM.

Note: Mind that parameters inside [] are optional.

HTML

<div id='list-wrapper'>
    <h3>Largest Countries in the World</h3>
    <ol>
        <li>Russia</li>
        <li>Canada</li>
        <li>USA</li>
        <li>China</li>
        <li>Brazil</li>
    </ol>
</div>

Result

We can use .remove() to remove the list and its content from the DOM. The following scripts are included just before the closing body tag:

jQuery

<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script>
    // Select list
    var list = $('#list-wrapper').children('ol');
    // Remove the list itself, as well as everything inside it
    list.remove();
</script>

Result

Note: For more methods please visit the jQuery API at this link.

Adding DOM elements


Introduction

Adding DOM elements with vanilla JavaScript is complicated. We need to select a target element, create the new element, add content to the new element and finally add the new element before/after our target element. On the other hand, with jQuery things are easier. We can do the same by writing less code.

API methods being used:

.append(content, [content])
Insert content, specified by the parameter, to the end of each element in the set of matched elements.
.prepend(content, [content])
Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.
.insertBefore(target)
Insert every element in the set of matched elements before the target.
.insertAfter(target)
Insert every element in the set of matched elements after the target.
.before(content[,content])
Insert content, specified by the parameter, before each element in the set of matched elements.
.after(content[,content])
Insert content, specified by the parameter, after each element in the set of matched elements.

Note: Mind that parameters inside [] are optional. Also, the .before()|.after() and .insertBefore()|.insertAfter() methods perform the same task. The major difference is in the syntax.

Example 1

HTML

<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'>
        <title>Basic JQuery</title>
    </head>
    <body>
        <h3>Adding childs</h3>
        <div id='example-1'>
            <hr>
        </div>
        <h3>Adding siblings</h3>
        <div id='example-2'>
            <hr>
        </div>
    </body>
</html>

The following scripts are included just before the closing body tag:

jQuery

<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script>
    // Add child elements
    $('#example-1').append('<p>.append()</p>');
    $('#example-1').prepend('<p>.prepend()</p>');

    // Add sibling elements
    var content1 = $('<p>.insertAfter()</p>');
    var content2 = $('<p>.insertBefore()</p>');
    content1.insertAfter('#example-2');
    content2.insertBefore('#example-2');
</script>

Result (DOM)

<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'>
        <title>Basic JQuery</title>
    </head>
    <body>
        <h3>Adding childs</h3>
        <div id='example-1'>
            <p>.prepend()</p>
            <hr>
            <p>.append()</p>
        </div>
        <h3>Adding siblings</h3>
        <p>.insertBefore()</p>
        <div id='example-2'>
            <hr>
        </div>
        <p>.insertAfter()</p>
    </body>
</html>

Example 2

HTML

<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'>
        <title>Basic JQuery</title>
    </head>
    <body>
        <div id='family-tree'>
            <div id='family1'>
                <h3>Family1</h3>
                <div id='alex'>
                    <h4>Alex</h4>
                    <div id='jane'>
                        <h5>Jane</h5>
                    </div>
                </div>
                <div id='taylor'>
                    <h4>Taylor</h4>
                    <div id='bob'>
                        <h5>Bob</h5>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>

Result

Using jQuery we are going to add the following elements to the DOM:

  1. #family2 should be a sibling of and come after #family1.
  2. #bruce should be the only immediate child of #family2.
  3. #bruce should have two <div>s as children, #madison and #hunter.

The following scripts are included just before the closing body tag:

jQuery

<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script>
    // Add '#family2' after '#family1'
    var content = $('<div id='family2'><h3>Family2</h3></div>');
    content.insertAfter('#family1');

    // Add '#bruce' as a child of '#family2'
    $('#family2').append('<div id='bruce'><h4>Bruce</h4></div>');

    // Add '#madison' as a child of '#bruce'
    $('#bruce').append('<div id='madison'><h5>Madison</h5></div>');

    // Add '#hunter' as a child of '#bruce'
    $('#bruce').append('<div id='hunter'><h5>Hunter</h5></div>');
</script>

Result

Note: For more methods please visit the jQuery API at this link.

Ad1
advertisement
Ad2
advertisement
Ad3
advertisement
Ad4
advertisement
Ad5
advertisement
Ad6
advertisement