JavaScript - jQuery - 03 - HTML

revision:


jQuery - DOM manipulation

jQuery contains powerful methods for changing and manipulating HTML elements and attributes.

One very important part of jQuery is the possibility to manipulate the DOM, as jQuery comes with a bunch of DOM related methods that make it easy to access and manipulate elements and attributes.

jQuery - "get" content and attributes.

A very important part of jQuery is the possibility to manipulate the DOM. jQuery comes with a bunch of DOM related methods that make it easy to access and manipulate elements and attributes.

Three simple, but useful, jQuery methods for DOM manipulation are: text(), html(), and val().

text() - sets or returns the text content of selected elements;

html() - sets or returns the content of selected elements (including HTML markup);

val() - sets or returns the value of form fields.

The following example demonstrates how to get content with the jQuery text() and html() methods:

example:

This is some bold text in a paragraph.

Codes:
                <div>
                    <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>
                    <p id="jQ01" style="margin-left:4vw;"></p>
                    <p id="jQ02" style="margin-left:4vw;"></p>
                </div>
                <script>
                    $(document).ready(function(){
                        $("#btn1").click(function(){
                            alert("Text: " + $("#test").text());
                            $("#jQ01").append("text:" + $("#test").text());
                        });
                        $("#btn2").click(function(){
                            alert("HTML: " + $("#test").html());
                            $("#jQ02").append("HTML:" + $("#test").html());
                        });
                   }); 
                </script>
            

The following example demonstrates how to get the value of an input field with the jQuery val() method:

example:

Name:

Codes:
                <div>
                    <p>Name: <input type="text" id="test2" value="Mickey Mouse"></p>
                    <button id="btn3">show value</button>
                </div>
                <script>
                    $(document).ready(function(){
                        $("#btn3").click(function(){
                            alert("Value: " + $("#test2").val());
                        });
                    });
                </script>
            

Get attributes - attr()

The following example demonstrates how to get the value of the href attribute in a link:

example:

my website

code:
                <div>
                    <p><a href="https://www.lwitters.com" id="website">my website</a></p>
                    <button id="btn_A">Show href Value</button>
                </div>
                <script>
                    $(document).ready(function(){
                        $("#btn_A").click(function(){
                            alert($("#website").attr("href"));
                        });
                    });
                </script>
            

jQuery - "set" content and attributes

The same three methods can be used to set content: text(), html(), val().

text() - sets or returns the text content of selected elements;

html() - sets or returns the content of selected elements (including HTML markup);

val() - sets or returns the value of form fields.

The following example demonstrates how to set content with the jQuery text(), html(), and val() methods.

example:

This is a paragraph.

This is another paragraph.

Input field:

Codes:

                <div>        
                    <p id="test4">This is another paragraph.</p>
                    <p>Input field: <input type="text" id="test6" value="Mickey Mouse"></p>
                    <button id="btn4">set text</button>
                    <button id="btn5">set HTML</button>
                    <button id="btn6">set value</button>
                    <p id="jQ03"></p>
                </div>
                <script>
                    $(document).ready(function(){
                        $("#btn4").click(function(){
                            $("#test4").text("Hello world!");
                        });
                        $("#btn5").click(function(){
                            $("#test5").html("<b>Hello world!</b>");
                        });
                        $("#btn6").click(function(){
                            $("#test6").val("Dolly Duck");
                        });
                    });
                </script>
            

All three jQuery methods (i.e text(), html(), and val() ) also come with a callback function.

The callback function has two parameters:

the index of the current element in the list of elements selected:

the original (old) value.

You then return the string you wish to use as the new value from the function.

The following example demonstrates text() and html() with a callback function.

example:

This is a bold paragraph.

This is another bold paragraph.

Codes:

                <div>
                    <p id="test7">This is a <b>bold</b> paragraph.</p>
                    <p id="test8">This is another <b>bold</b> paragraph.</p>
                    <button id="btn7">show old/new text</button>
                    <button id="btn8">show old/new HTML</button>
                </div>
                <script>
                    $(document).ready(function(){
                        $("#btn7").click(function(){
                            $("#test7").text(function(i, origText){
                            return "Old text: " + origText + " New text: Hello world! (index: " + i + ")"; 
                            });
                        });
        
                        $("#btn8").click(function(){
                            $("#test8").html(function(i, origText){
                            return "Old html: " + origText + " New html: Hello <b>world!</b> (index: " + i + ")"; 
                            });
                        });
                    });
                </script>
            

Set/change attributes - attr()

The following example demonstrates how to change (set) the value of the href attribute in a link:

example:

my website

Mouse over the link (or click on it) to see that the value of the href attribute has changed.

code:
                <div>
                    <p><a href="https://www.lwitters.com" id="website2">my website</a></p>
                    <button id="btn_B">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>
                </div>
                <script>
                    $(document).ready(function(){
                        $("#btn_B").click(function(){
                            $("#website2").attr("href", "https://lwitters-1.com");
                        });
                    });
                </script>
            

jQuery - "add" elements

With jQuery, it is easy to add new elements/content. Four jQuery methods are used to add new content:

append() - inserts content at the end of the selected elements;

prepend() - inserts content at the beginning of the selected elements;

after() - inserts content after the selected elements;

before() - inserts content before the selected elements.

The jQuery append() method inserts content AT THE END of the selected HTML elements.

example:

This is a paragraph.

This is another paragraph.

  1. List item 1
  2. List item 2
  3. List item 3

Codes:

                <div>
                    <p class="p9">This is a paragraph.</p>
                    <p class="p9">This is another paragraph.</p>
                    <ol>
                        <li>List item 1</li>
                        <li>List item 2</li>
                        <li>List item 3</li>
                    </ol>
                    <button id="btn9">append text</button>
                    <button id="btn10">append list items</button>
                </div>
                <script>
                    $(document).ready(function(){
                        $("#btn9").click(function(){
                            $(".p9").append(" - <b>Appended text</b>.");
                        });
                        $("#btn10").click(function(){
                            $("ol").append("<li><b>Appended item</b></li>");
                        });
                    });
                </script>
            

The jQuery prepend() method inserts content AT THE BEGINNING of the selected HTML elements.

example:

This is a paragraph.

This is another paragraph.

  1. List item 1
  2. List item 2
  3. List item 3
Codes:
                <div>
                    <p class="p10">This is a paragraph.</p>
                    <p class="p10">This is another paragraph.</p>
                    <ol class="ol1">
                        <li>List item 1</li>
                        <li>List item 2</li>
                        <li>List item 3</li>
                    </ol>
                    <button id="btn11">prepend text</button>
                    <button id="btn12">prepend list item</button>
                </div>
                <script>
                    $(document).ready(function(){
                        $("#btn11").click(function(){
                            $(".p10").prepend("<b>Prepended text</b>. ");
                        });
                        $("#btn12").click(function(){
                            $(".ol1").prepend("<li>Prepended item</li>");
                        });
                    });
                </script>
            

Add several new elements with append() and prepend().

Both the append() and prepend() methods can take an infinite number of new elements as parameters. The new elements can be generated with text/HTML, with jQuery, or with JavaScript code and DOM elements.

In the following example, we create several new elements. The elements are created with text/HTML, jQuery, and JavaScript/DOM. Then we append the new elements to the text with the append() method (this would have worked for prepend() too).

example:

This is a paragraph.

Codes:

                <div>
                    <p class="p11">This is a paragraph.</p>
                    <button onclick="appendText()">append text</button>
                </div>
                <script>
                    function appendText() {
                        var txt1 = "<p>Text.</p>";        // Create text with HTML
                        var txt2 = $("<p></p>").text("Text.");  // Create text with jQuery
                        var txt3 = document.createElement("p");
                        txt3.innerHTML = "Text.";         // Create text with DOM
                        $(".p11").append(txt1, txt2, txt3);   // Append new elements
                    }
                </script>
            

The jQuery after() method inserts content AFTER the selected HTML elements.

The jQuery before() method inserts content BEFORE the selected HTML elements.

example:
jQuery

Codes:

                <div>
                    <img src="../../pics/1.jpg" alt="jQuery" width="100" height="140"><br><br>
                    <button id="btn13">insert before</button>
                    <button id="btn14">insert after</button>
                </div>
                <script>
                    $(document).ready(function(){
                        $("#btn13").click(function(){
                            $("img").before("<b>Before</b>");
                        });
        
                        $("#btn14").click(function(){
                            $("img").after("<i>After</i>");
                        });
                    });
                </script>
            

Add several new elements with after() and before().

Both the after() and before() methods can take an infinite number of new elements as parameters. The new elements can be generated with text/HTML, with jQuery, or with JavaScript code and DOM elements.

In the following example, we create several new elements. The elements are created with text/HTML, jQuery, and JavaScript/DOM. Then we insert the new elements to the text with the after() method (this would have worked for before() too).

example:
jQuery

Click the button to insert text after the image.

Codes:
                <div>
                    <img id="img1" src="../../pics/1.jpg" alt="jQuery" width="100" height="140" style="margin-bottom: 1vw;">
                    <p style="margin-top: 1vw;">Click the button to insert text after the image.</p>
                    <button id="btn15" onclick="afterText()">Insert after</button>
                </div>
                <script>
                    function afterText() {
                        var txt1 = "<b>I </b>";           // Create element with HTML
                        var txt2 = $("<i></i>").text("love ");  // Create with jQuery
                        var txt3 = document.createElement("b");   // Create with DOM
                        txt3.innerHTML = "jQuery!";
                        $("#img1").after(txt1, txt2, txt3);    // Insert new elements after img
                    }
                </script>
            

jQuery - remove elements

To remove elements and content, there are mainly two jQuery methods:

remove() - removes the selected element (and its child elements);

empty() - removes the child elements from the selected element

The jQuery remove() method removes the selected element(s) and its child elements.

example:
This is some text in the div.

This is a paragraph in the div.

This is another paragraph in the div.


Codes:
                <div>
                    <div id="div11a" style="height:8vw;width:25vw;border:1px solid black;background-color:yellow; margin-left: 4vw;">
                        This is some text in the div.
                        <p style="margin-top: 1vw;">This is a paragraph in the div.</p>
                        <p style="margin-top: 1vw;">This is another paragraph in the div.</p>
                    </div>
                    <br>
                    <button id="button1">Remove div element</button>
                   
                </div>
                <script>
                    $(document).ready(function(){
                        $("#button1").click(function(){
                            $("#div11a").remove();
                        });
                    });
                </script>
            

The jQuery empty() method removes the child elements of the selected element(s).

example:
This is some text in the div.

This is a paragraph in the div.

This is another paragraph in the div.


Codes:
                <div>
                    <div id="div11b" style="height:8vw;width:25vw;border:1px solid black;background-color:yellow;">
                        This is some text in the div.
                        <p style="margin-top: 1vw;">This is a paragraph in the div.</p>
                        <p style="margin-top: 1vw;">This is another paragraph in the div.</p>
                    </div>
                    <br>
                    <button id="button2">Empty the div element</button>
                </div>
                <script>
                    $(document).ready(function(){
                        $("#button2").click(function(){
                            $("#div11b").empty();
                        });
                    });
                </script>
            

The jQuery remove() method also accepts one parameter, which allows you to filter the elements to be removed. The parameter can be any of the jQuery selector syntaxes.

The following example removes all "p" elements with class="test".

example:

This is a paragraph.

This is another paragraph.

This is another paragraph.

Codes:
                <div>
                    <p>This is a paragraph.</p>
                    <p class="testA" style="color:red">This is another paragraph.</p>
                    <p class="testA" style="color:red">This is another paragraph.</p>
                    <button id="button3">Remove all "p" elements with class="testA"</button>
                </div>   
                <script>
                    $(document).ready(function(){
                        $("#button3").click(function(){
                            $(".testA").remove(".testA");
                        });
                    });
                </script> 
            

This example removes all "p" elements with class="test" and class="demo".

example:

This is a paragraph.

This is p element with class="test".

This is p element with class="test".

This is p element with class="demo".

Codes:>
                <div>
                    <p >This is a paragraph.</p>
                    <p class=" pro testB" style="color:red;">This is p element with class="test".</p>
                    <p class=" pro testB" style="color:red;">This is p element with class="test".</p>
                    <p class=" pro demoB" style="color:green;">This is p element with class="demo".</p>
                    <button id="button4">Remove all p elements with class="test" and class="demo"</button>
                </div>
                <script>
                    $(document).ready(function(){
                        $("#button4").click(function(){
                            $(".pro").remove(".testB, .demoB");
                        });
                    });
                </script>
            

jQuery - "get" and "set" CSS classes

jQuery has several methods for CSS manipulation:

addClass() - adds one or more classes to the selected elements;

removeClass() - removes one or more classes from the selected elements;

toggleClass() - toggles between adding/removing classes from the selected elements;

css() - sets or returns the style attribute

The following example shows how to add class attributes to different elements. Of course you can select multiple elements, when adding classes:

example:

Heading 1

Heading 2

This is a paragraph.

This is another paragraph.

This is some important text!

Codes:
                <div>
                    <h4 class="h1">Heading 1</h4>
                    <h5 class="h1">Heading 2</h5>
                    <p class="pt1">This is a paragraph.</p>
                    <p class="pt1">This is another paragraph.</p>
                    <div class="dv">This is some important text!</div><br>
                    <button id="b12">Add classes to elements</button>
                </div>
                <script>
                    $(document).ready(function(){
                        $("#b12").click(function(){
                            $(".h1, .pt1").addClass("blue");
                            $(".dv").addClass("important");
                        });
                    });
                </script>
                

You can also specify multiple classes within the addClass() method:

example:
This is some text.
This is some text.

Codes:
                <div>
                    <div id="div1aa">This is some text.</div>
                    <div id="div2aa">This is some text.</div>
                    <br>
                    <button id="b13">Add classes to first div element</button>
                </div>
                <script>
                    $(document).ready(function(){
                        $("#b13").click(function(){
                            $("#div1aa").addClass("important blue");
                        });
                    });
                </script>
            

The following example shows how to remove a specific class attribute from different elements.

example:
Heading 1
Heading 2

This is a paragraph.

This is another paragraph.

Codes:
                <div>
                    <h5 class="blue">Heading 1</h5>
                    <h6 class="blue">Heading 2</h6>
                    <p  class="blue">This is a paragraph.</p>
                    <p class="paaa">This is another paragraph.</p>
                    <button id="b14">Remove class from elements</button>
                </div>
                <script>
                    $(document).ready(function(){
                        $("#b14").click(function(){
                            $("h5, h6, p").removeClass("blue");
                        });
                    });
                </script>
            

The following example shows how to remove a specific class attribute from different elements.

example:
Heading 1
Heading 2

This is a paragraph.

This is another paragraph.

Codes:
                <div>
                    <h5 class="hh">Heading 1</h5>
                    <h6 class="hh">Heading 2</h6>
                    <p class="aa">This is a paragraph.</p>
                    <p class="aa">This is another paragraph.</p>
                    <button id="b15">Toggle class</button>
                </div>
                <script>
                    $(document).ready(function(){
                        $("#b15").click(function(){
                            $(".hh, .aa").toggleClass("blue");
                        });
                    });
                </script>
            

The css() method sets or returns one or more style properties for the selected elements.

To return the value of a specified CSS property, use the following syntax: css("propertyname");.

The following example will return the background-color value of the FIRST matched element:

example:
This is a heading

This is a paragraph.

This is a paragraph.

This is a paragraph.

Codes:
                <div>  
                    <h5 id="hhh">This is a heading</h5>
                    <p style="background-color:#ff0000" class="bb">This is a paragraph.</p>
                    <p style="background-color:#00ff00" class="bb">This is a paragraph.</p>
                    <p style="background-color:#0000ff" class="bb">This is a paragraph.</p>
                    <button id="b16">Return background-color of p</button>
                </div>
                <script>
                    $(document).ready(function(){
                        $("#b16").click(function(){
                            alert("Background color = " + $("p").css("background-color"));
                        });
                    });
                </script>
            

To set a specified CSS property, use the following syntax:css("propertyname", "value");.

The following example will set the background-color value for ALL matched elements:

example:
This is a heading

This is a paragraph.

This is a paragraph.

This is a paragraph.

This is a paragraph.

Codes:
                <div>
                    <h5 id="hhhh">This is a heading</h5>
                    <p class="bbb" style="background-color:#ff0000">This is a paragraph.</p>
                    <p class="bbb" style="background-color:#00ff00">This is a paragraph.</p>
                    <p class="bbb" style="background-color:#0000ff">This is a paragraph.</p>
                    <p >This is a paragraph.</p>
                    <button id="b17">Set background-color of p</button>
                </div>
                <script>
                    $(document).ready(function(){
                        $("#b17").click(function(){
                            $(".bbb").css("background-color", "yellow");
                        });
                    });
                </script>
            

To set multiple CSS properties, use the following syntax::css({"propertyname":"value","propertyname":"value",...});.

The following example will set a background-color and a font-size for ALL matched elements:

example:
This is a heading

This is a paragraph.

This is a paragraph.

This is a paragraph.

This is a paragraph.

Codes:
                <div>
                    <h5>This is a heading</h5>
                    <p class="bbb1" style="background-color:#ff0000">This is a paragraph.</p>
                    <p class="bbb1" style="background-color:#00ff00">This is a paragraph.</p>
                    <p class="bbb1" style="background-color:#0000ff">This is a paragraph.</p>
                    <p>This is a paragraph.</p>
                    <button id="b18"  style="margin-left: 4vw;">Set multiple styles for p</button>
                </div>
                <script>
                    $(document).ready(function(){
                        $("#b18").click(function(){
                            $(".bbb1").css({"background-color": "yellow", "font-size": "200%"});
                        });
                    });           
                </script>    
            

jQuery - dimensions

jQuery has several important methods for working with dimensions: width(), height(), innerWidth(), innerHeight(), outerWidth(), outerHeight().

The width() method sets or returns the width of an element (excludes padding, border and margin).

The height() method sets or returns the height of an element (excludes padding, border and margin).

The following example returns the width and height of a specified "div" element:

example:

width() - returns the width of an element.

height() - returns the height of an element.

Codes:
                <div>
                    <div id="div1z"></div>
                    <br>
                    <p class="bbb2">width() - returns the width of an element.</p>
                    <p class="bbb2">height() - returns the height of an element.</p>
                    <button id="b19">Display dimensions of div</button>     
                </div>
                <script>
                    $(document).ready(function(){
                        $("#b19").click(function(){
                            var txt = "";
                            txt += "Width of div: " + $("#div1z").width() + "</br>";
                            txt += "Height of div: " + $("#div1z").height();
                            $("#div1z").html(txt);
                        });
                    });
                </script>
            

The innerWidth() method returns the width of an element (includes padding).

The innerHeight() method returns the height of an element (includes padding).

The following example returns the inner-width/height of a specified "div" element:

example:

innerWidth() - returns the width of an element (includes padding).

innerHeight() - returns the height of an element (includes padding).

Codes:
                <div>
                    <div id="div1y"></div>
                    <br>
                    <p class="bbb3">innerWidth() - returns the width of an element (includes padding).</p>
                    <p class="bbb3">innerHeight() - returns the height of  an element (includes padding).</p>
                    <button id="b20" style="margin-left:4vw;">Display dimensions of div</button>
                </div>
                <script>
                    $(document).ready(function(){
                        $("#b20").click(function(){
                            var txt = "";
                            txt += "Width of div: " + $("#div1y").width() + "</br>";
                            txt += "Height of div: " + $("#div1y").height() + "</br>";
                            txt += "Inner width of div: " + $("#div1y").innerWidth() + "</br>";
                            txt += "Inner height of div: " + $("#div1y").innerHeight();
                            $("#div1y").html(txt);
                        });
                    });
                </script>
            

The outerWidth() method returns the width of an element (includes padding and border).

The outerHeight() method returns the height of an element (includes padding and border).

The following example returns the outer-width/height of a specified "div" element:

example:

outerWidth() - returns the width of an element (includes padding and border).

outerHeight() - returns the height of an element (includes padding and border).

Codes:
                <div>
                    <div id="div1x"></div>
                    <br>
                    <p class="bbb4">outerWidth() - returns the width of an element (includes padding and border).</p>
                    <p class="bbb4">outerHeight() - returns the height of an element (includes padding and border).</p>
                    <button id="b21">Display dimensions of div</button>         
                </div>
                <script>
                    $(document).ready(function(){
                        $("#b21").click(function(){
                            var txt = "";
                            txt += "Width of div: " + $("#div1x").width() + "</br>";
                            txt += "Height of div: " + $("#div1x").height() + "</br>";
                            txt += "Outer width of div: " + $("#div1x").outerWidth() + "</br>";
                            txt += "Outer height of div: " + $("#div1x").outerHeight();
                            $("#div1x").html(txt);
                        });
                    });    
                </script>
            

The outerWidth(true) method returns the width of an element (includes padding, border, and margin).

The outerHeight(true) method returns the height of an element (includes padding, border, and margin).

example:

outerWidth(true) - returns the width of an element (includes padding, border, and margin).

outerHeight(true) - returns the height of an element (includes padding, border, and margin).

Codes:
                <div>
                    <div id="div1w"></div>
                    <br>
                    <p class="bbb5">outerWidth(true) - returns the width of an element (includes padding, border, and margin).</p>
                    <p class="bbb5">outerHeight(true) - returns the height of an element (includes padding, border, and margin).</p>
                    <button id="b22">Display dimensions of div</button>         
                </div>
                <script>
                    $(document).ready(function(){
                        $("#b22").click(function(){
                            var txt = "";
                            txt += "Width of div: " + $("#div1w").width() + "</br>";
                            txt += "Height of div: " + $("#div1w").height() + "</br>";
                            txt += "Outer width of div (margin included): " + $("#div1w").outerWidth(true) + "</br>";
                            txt += "Outer height of div (margin included): " + $("#div1w").outerHeight(true);
                            $("#div1w").html(txt);
                        });
                    });
                </script>
            

P.S. outerWidth() includes styling, i.e. margin-left setting.

The following example returns the width and height of the document (the HTML document) and window (the browser viewport):

example:
Codes:
                <div>  
                    <button id="b23">Display dimensions of document and window</button>
                </div>
                <script>
                    $(document).ready(function(){
                        $("#b23").click(function(){
                            var txt = "";
                            txt += "Document width/height: " + $(document).width();
                            txt += "x" + $(document).height() + "\n";
                            txt += "Window width/height: " + $(window).width();
                            txt += "x" + $(window).height();
                            alert(txt);
                        });
                    });
                </script>
            

The following example sets the width and height of a specified <div> element:

example:

Codes:
                <div>
                    <div style="margin-left: 4vw;" id="div1v"></div>
                    <br>
                    <button id="b24" style="margin-left:4vw;">Resize div</button>          
                </div>
                <script>
                    $(document).ready(function(){
                        $("#b24").click(function(){
                            $("#div1v").width(500).height(500);
                        });
                    });    
                </script>