Interacting with the DOM – 3

Posted: May 10, 2014 in jQuery
Tags: , , ,

jQuery is a very powerful tool which provides a variety of DOM traversal methods to help us select elements in a document randomly as well as in sequential method.

Iterating through nodes

.each(function(index, Element) is used to iterate through jQuery objects:

 $(document).ready(function () {
            $('div').each(function (index) {
                alert(index + "=" + $(this).text());
            });
        });

 

 $(document).ready(function () {
            $('div').each(function (index, element) {
                alert(index + "=" + $(element).text());
            });
        });

 

Modifying DOM object Properties

The this.propertyName statement can be used to modify an object’s properties directly.

 $(document).ready(function () {
            $('div').each(function (index) {
                this.title = "Cutom Index" + index;
            });
        });

 

The above code iterates through each div and modifies the title. If the property does not exist, it will be added dynamically

Four key methods handle inserting nodes into elements

.append()
.appendTo()
.prepend()
.PrependTo()
 jQuery append()

The below example insert content at the end of the selected HTML elements.

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("#btn1").click(function () {
                $("p").append(" <b>Appended text</b>.");
            });
            $("#btn2").click(function () {
                $("ol").append("<li>Appended item</li>");
            });
        });
    </script>
</head>
<body>
    <p>
        This is a paragraph.</p>
    <p>
        This is another paragraph.</p>
    <ol>
        <li>List item 1</li>
        <li>List item 2</li>
        <li>List item 3</li>
    </ol>
    <button id="btn1">
        Append text</button>
    <button id="btn2">
        Append list items</button>
</body>
</html>

 

jQuery appendTo()
$(‘<span>(office)</span>’).appendTo(‘.officePhone’);

Or

$(‘officePhone’).append($(‘<span>(office)</span>’);
 jQuery prepend()

The below example Insert content at the beginning of the selected HTML elements

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("#btn1").click(function () {
                $("p").prepend("<b>Prepended text</b>. ");
            });
            $("#btn2").click(function () {
                $("ol").prepend("<li>Prepended item</li>");
            });
        });
    </script>
</head>
<body>
    <p>
        This is a paragraph.</p>
    <p>
        This is another paragraph.</p>
    <ol>
        <li>List item 1</li>
        <li>List item 2</li>
        <li>List item 3</li>
    </ol>
    <button id="btn1">
        Prepend text</button>
    <button id="btn2">
        Prepend list item</button>
</body>
</html>
jQuery prependTo()
 $(‘<span>Phone:</span>’).prependTo(‘.Phone’);

Or

$(‘Phone’).prepend($(‘<span>Phone:</span>’);

 

jQuery wrap()
<div class=”state”>Kansas</div>
$(‘.state).wrap(‘<div class=”USState”/>’);
The above action would result into as below
<div class="”USState”" />
<div class="”state”">Kansas</div>
</div>

 

jQuery after() and before()

The below example Insert content after and before the selected HTML elements

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("#btn1").click(function () {
                $("img").before("<b>Before</b>");
            });
 
            $("#btn2").click(function () {
                $("img").after("<i>After</i>");
            });
        });
    </script>
</head>
<body>
    <img src="/images/w3jquery.gif" alt="jQuery" width="100" height="140">
    <br>
    <br>
    <button id="btn1">
        Insert before</button>
    <button id="btn2">
        Insert after</button>
</body>
</html>
jQuery remove()

The below example remove the selected element(s)

 <!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("#div1").remove();
            });
        });
    </script>
</head>
<body>
    <div id="div1" style="height: 100px; width: 300px; border: 1px solid black; background-color: yellow;">
        This is some text in the div.
        <p>
            This is a paragraph in the div.</p>
        <p>
            This is another paragraph in the div.</p>
    </div>
    <br>
    <button>
        Remove div element</button>
</body>
</html>

 

jQuery empty()

The below example remove all child elements of the selected element(s).

 <!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("#div1").empty();
            });
        });
    </script>
</head>
<body>
    <div id="div1" style="height: 100px; width: 300px; border: 1px solid black; background-color: yellow;">
        This is some text in the div.
        <p>
            This is a paragraph in the div.</p>
        <p>
            This is another paragraph in the div.</p>
    </div>
    <br>
    <button>
        Empty the div element</button>
</body>
</html>

Filter the elements to be removed
<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("p").remove(".italic");
            });
        });
    </script>
</head>
<body>
    <p>
        This is a paragraph in the div.</p>
    <p class="italic">
        <i>This is another paragraph in the div.</i></p>
    <p class="italic">
        <i>This is another paragraph in the div.</i></p>
    <button>
        Remove all p elements with class="italic"</button>
</body>
</html>

jQuery – return width() and height()

Return the width and height of a specified element.

Return the width and height of a specified element
<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                var txt = "";
                txt += "Width of div: " + $("#div1").width() + "</br>";
                txt += "Height of div: " + $("#div1").height();
                $("#div1").html(txt);
            });
        });
    </script>
</head>
<body>
    <div id="div1" style="height: 100px; width: 300px; padding: 10px; margin: 3px; border: 1px solid blue;
        background-color: lightblue;">
    </div>
    <br>
    <button>
        Display dimensions of div</button>
    <p>
        width() - returns the width of an element.</p>
    <p>
        height() - returns the height of an element.</p>
</body>
</html>

 

Sets the width and height of a specified element
<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("#div1").width(500).height(500);
            });
        });
    </script>
</head>
<body>
    <div id="div1" style="height: 100px; width: 300px; padding: 10px; margin: 3px; border: 1px solid blue;
        background-color: lightblue;">
    </div>
    <br>
    <button>
        Resize div</button>
</body>
</html>

 

jQuery – return innerWidth() and innerHeight()

Return the inner-width/height of a specified element.

jQuery – return outerWidth() and outerHeight()

Return the outer-width/height of a specified element.

jQuery – return outerWidth(true) and outerHeight(true)

Return the outer-width/height (including margins) of a specified element.

jQuery – return width() and height() of document and window

Return the width and height of the document (the HTML document) and window (the browser viewport).

jQuery – set width() and height()

Sets the width and height of a specified element.

 

jQuery load()

The below example load the content of a file into a <div> element.

 <!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("#div1").load("demo_test.txt");
            });
        });
    </script>
</head>
<body>
    <div id="div1">
        <h2>
            Let jQuery AJAX Change This Text</h2>
    </div>
    <button>
        Get External Content</button>
</body>
</html>

 jQuery load() with callback

The below example demonstrates the use of the jQuery load() method with a callback function.

 <!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("#div1").load("demo_test.txt", function (responseTxt, statusTxt, xhr) {
                    if (statusTxt == "success")
                        alert("External content loaded successfully!");
                    if (statusTxt == "error")
                        alert("Error: " + xhr.status + ": " + xhr.statusText);
                });
            });
        });
    </script>
</head>
<body>
    <div id="div1">
        <h2>
            Let jQuery AJAX Change This Text</h2>
    </div>
    <button>
        Get External Content</button>
</body>
</html>

 jQuery text() and html() – Get content

The below example get content with the jQuery text() and html() methods.

 <!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("#btn1").click(function () {
                alert("Text: " + $("#test").text());
            });
            $("#btn2").click(function () {
                alert("HTML: " + $("#test").html());
            });
        });
    </script>
</head>
<body>
    <p id="test">
        This is some <b>bold</b> text in a paragraph.</p>
    <button id="btn1">
        Show Text</button>
    <button id="btn2">
        Show HTML</button>
</body>
</html>

 

jQuery val() – Get content

The below example get the value of a form field with the jQuery val() method.

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                alert("Value: " + $("#test").val());
            });
        });
    </script>
</head>
<body>
    <p>
        Name:
        <input type="text" id="test" value="Mickey Mouse"></p>
    <button>
        Show Value</button>
</body>
</html>

 

jQuery attr() – Get attribute value

The below example get the value of an attribute with the jQuery attr() method.

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                alert($("#w3s").attr("href"));
            });
        });
    </script>
</head>
<body>
    <p>
        <a href="http://www.w3schools.com" id="w3s">W3Schools.com</a></p>
    <button>
        Show href Value</button>
</body>
</html>

 

jQuery text(), html(), and val() – Set content

The below example set content with the jQuery text(), html() and val() methods.

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("#btn1").click(function () {
                $("#test1").text("Hello world!");
            });
            $("#btn2").click(function () {
                $("#test2").html("<b>Hello world!</b>");
            });
            $("#btn3").click(function () {
                $("#test3").val("Dolly Duck");
            });
        });
    </script>
</head>
<body>
    <p id="test1">
        This is a paragraph.</p>
    <p id="test2">
        This is another paragraph.</p>
    <p>
        Input field:
        <input type="text" id="test3" value="Mickey Mouse"></p>
    <button id="btn1">
        Set Text</button>
    <button id="btn2">
        Set HTML</button>
    <button id="btn3">
        Set Value</button>
</body>
</html>

 

To modify multiple attributes, pass a JSON object containing name/value pairs

 

  $('img').attr{
                title = "Cutom title",
                style = "border: 2px solid green;"
            });

 

jQuery text() and html() – Set content with a callback function

The below example set content + using a callback function inside text() and html().

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("#btn1").click(function () {
                $("#test1").text(function (i, origText) {
                    return "Old text: " + origText + " New text: Hello world! (index: " + i + ")";
                });
            });
 
            $("#btn2").click(function () {
                $("#test2").html(function (i, origText) {
                    return "Old html: " + origText + " New html: Hello <b>world!</b> (index: " + i + ")";
                });
            });
 
        });
    </script>
</head>
<body>
    <p id="test1">
        This is a <b>bold</b> paragraph.</p>
    <p id="test2">
        This is another <b>bold</b> paragraph.</p>
    <button id="btn1">
        Show Old/New Text</button>
    <button id="btn2">
        Show Old/New HTML</button>
</body>
</html>

 

jQuery attr() – Set attribute value

The below example set attribute value with the jQuery attr() method.

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("#w3s").attr("href", "https://kborra.wordpress.com/category/jquery/");
            });
        });
    </script>
</head>
<body>
    <p>
        <a href="https://kborra.wordpress.com/" id="w3s">Kishore Blog</a></p>
    <button>
        Change href Value</button>
    <p>
        Mouse over the link (or click on it) to see that the value of the href attribute
        has changed.</p>
</body>
</html>

 

jQuery attr() – Set multiple attribute values

The below example set multiple attribute values with the jQuery attr() method.

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("#w3s").attr({
                    "href": " https://kborra.wordpress.com/category/jquery/",
                    "title": "Kborra jQuery Tutorial"
                });
            });
        });
    </script>
</head>
<body>
    <p>
        <a href="https://kborra.wordpress.com/" id="w3s">Kishore Blog</a></p>
    <button>
        Change href and title</button>
    <p>
        Mouse over the link to see that the href attribute has changed and a title attribute
        is set.</p>
</body>
</html>

 

jQuery attr() – Set attribute value with a callback function

The below example set attribute value + using a callback function inside attr().

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("#w3s").attr("href", function (i, origValue) {
                    return origValue + "/jquery";
                });
            });
        });
    </script>
</head>
<body>
    <p>
        <a href="https://kborra.wordpress.com/" id="w3s">Kishore Blog</a></p>
    <button>
        Change href Value</button>
    <p>
        Mouse over the link (or click on it) to see that the value of the href attribute
        has changed.</p>
</body>
</html>

 

jQuery hide()

The below example demonstrates the jQuery hide() method.

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("p").click(function () {
                $(this).hide();
            });
        });
    </script>
</head>
<body>
    <p>
        If you click on me, I will disappear.</p>
    <p>
        Click me away!</p>
    <p>
        Click me too!</p>
</body>
</html>

 

jQuery hide() and show()

The below example demonstrates jQuery hide() and show() methods.

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("#hide").click(function () {
                $("p").hide();
            });
            $("#show").click(function () {
                $("p").show();
            });
        });
    </script>
</head>
<body>
    <p>
        If you click on the "Hide" button, I will disappear.</p>
    <button id="hide">
        Hide</button>
    <button id="show">
        Show</button>
</body>
</html>

 

jQuery toggle()

jQuery toggle() toggles between hide() and show().

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("p").toggle();
            });
        });
    </script>
</head>
<body>
    <button>
        Toggle</button>
    <p>
        This is a paragraph with little content.</p>
    <p>
        This is another small paragraph.</p>
</body>
</html>

 

jQuery hide()

Another hide demonstration. How to hide parts of text.

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $(".ex .hide").click(function () {
                $(this).parents(".ex").hide("slow");
            });
        });
    </script>
    <style>
        div.ex
        {
            background-color: #e5eecc;
            padding: 7px;
            border: solid 1px #c3c3c3;
        }
    </style>
</head>
<body>
    <h3>
        Island Trading</h3>
    <div class="ex">
        <button class="hide">
            Hide me</button>
        <p>
            Contact: Helen Bennett<br>
            Garden House Crowther Way<br>
            London</p>
    </div>
    <h3>
        Paris spécialités</h3>
    <div class="ex">
        <button class="hide">
            Hide me</button>
        <p>
            Contact: Marie Bertrand<br>
            265, Boulevard Charonne<br>
            Paris</p>
    </div>
</body>
</html>

 

jQuery css() – return CSS property

Return the value of a specified CSS property from the FIRST matched element.

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                alert("Background color = " + $("p").css("background-color"));
            });
        });
    </script>
</head>
<body>
    <h2>
        This is a heading</h2>
    <p style="background-color: #ff0000">
        This is a paragraph.</p>
    <p style="background-color: #00ff00">
        This is a paragraph.</p>
    <p style="background-color: #0000ff">
        This is a paragraph.</p>
    <button>
        Return background-color of p</button>
</body>
</html>

 

jQuery css() – set CSS property

Set a specified CSS property for ALL matched elements.

 <!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("p").css("background-color", "yellow");
            });
        });
    </script>
</head>
<body>
    <h2>
        This is a heading</h2>
    <p style="background-color: #ff0000">
        This is a paragraph.</p>
    <p style="background-color: #00ff00">
        This is a paragraph.</p>
    <p style="background-color: #0000ff">
        This is a paragraph.</p>
    <p>
        This is a paragraph.</p>
    <button>
        Set background-color of p</button>
</body>
</html>
 jQuery css() – set CSS properties

Set multiple CSS properties for ALL matched elements.

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("p").css("background-color", "yellow");
            });
        });
    </script>
</head>
<body>
    <h2>
        This is a heading</h2>
    <p style="background-color: #ff0000">
        This is a paragraph.</p>
    <p style="background-color: #00ff00">
        This is a paragraph.</p>
    <p style="background-color: #0000ff">
        This is a paragraph.</p>
    <p>
        This is a paragraph.</p>
    <button>
        Set background-color of p</button>
</body>
</html>

 

Modifying CSS Classes

The four methods for working with CSS class attributes are

.addClass()
.hasClass()
.removeClass()

 

.addClass() adds one or more class names to the class attribute of each matched element

 

$(‘p’).addClass(‘classOne’);
$(‘p’).addClass(‘classOne classTwo’);

 

 

.hasClass() returns true if the selected element has a matching class that is specified

.removeClass() can remove one or more classes

 $(‘p’).removeClass(‘classOne’);
$(‘p’).removeClass(‘classOne classTwo’);
 $(‘p’).removeClass(); - removes all class attributes for the matching selector

 

 

JQuery DOM Traversing Methods:

Following table lists down useful methods which you can use to filter out various elements from a list of DOM elements:

Selector Description
eq( index ) Reduce the set of matched elements to a single element.
filter( selector ) Removes all elements from the set of matched elements that do not match the specified selector(s).
filter( fn ) Removes all elements from the set of matched elements that do not match the specified function.
is( selector ) Checks the current selection against an expression and returns true, if at least one element of the selection fits the given selector.
map( callback ) Translate a set of elements in the jQuery object into another set of values in a jQuery array (which may, or may not contain elements).
not( selector ) Removes elements matching the specified selector from the set of matched elements.
slice( start, [end] ) Selects a subset of the matched elements.

Following table lists down other useful methods which you can use to locate various elements in a DOM:

Selector Description
add( selector ) Adds more elements, matched by the given selector, to the set of matched elements.
andSelf( ) Add the previous selection to the current selection.
children( [selector]) Get a set of elements containing all of the unique immediate children of each of the matched set of elements.
closest( selector ) Get a set of elements containing the closest parent element that matches the specified selector, the starting element included.
contents( ) Find all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe.
end( ) Revert the most recent ‘destructive’ operation, changing the set of matched elements to its previous state .
find( selector ) Searches for descendent elements that match the specified selectors.
next( [selector] ) Get a set of elements containing the unique next siblings of each of the given set of elements.
nextAll( [selector] ) Find all sibling elements after the current element.
offsetParent( ) Returns a jQuery collection with the positioned parent of the first matched element.
parent( [selector] ) Get the direct parent of an element. If called on a set of elements, parent returns a set of their unique direct parent elements.
parents( [selector] ) Get a set of elements containing the unique ancestors of the matched set of elements (except for the root element).
prev( [selector] ) Get a set of elements containing the unique previous siblings of each of the matched set of elements.
prevAll( [selector] ) Find all sibling elements in front of the current element.
siblings( [selector] ) Get a set of elements containing all of the unique siblings of each of the matched set of elements.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s