Selecting Elements

Introduction

As mentioned previously, to select an item from a webpage, you can pass some information about it to the jQuery object as we will see in the next sections. When you have passed that information, the interpreter would look for at least one item that matches the information. If there is no item with the information, the jQuery object would be empty and no error would be produced.

Selecting an HTML Tag

Every HTML tag has a name. To select it for your jQuery code, pass the name of the tag as string to the jQuery object $(...). Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
<script src="Scripts/jquery-3.3.1.js"></script>
</head>
<body>
<form name="Exercise" method="post">
    <p><input type="button" id="btnSend" value="Send It" /></p>
</form>
<script type="text/javascript">
    $(document).ready(function () {
        $("input").click(function (event) {
            alert("Your time sheet has been submitted!");
        });
    });
</script>
</body>
</html>

A Variable for a jQuery Object

After selecting an element using the jQuery object, you can assign the selection to a locally declared variable. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Argument</title>
<script src="Scripts/jquery-3.3.1.js"></script>
</head>
<body>
<h1 class="text-center">Argumentative Qualifications</h1>

<div id="discussion">
 
</div>

<script type="text/javascript">
    $(document).ready(function () {
        var paragraph = $("div");
    });
</script>
</body>
</html>

Selecting an Element By its Identifier

As you may know already, to represent an HTML element, you can add an ID attribute to its start tag. Remember that, in a webpage, the identifiers must be unique. To select a tag by its identifier, pass the value of its identifier preceded with #. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Employee Record</title>
<script src="Scripts/jquery-3.3.1.js"></script>
</head>
<body>
<h1>Employee Record</h1>

<p><b>First Name:</b> <span id="fName"></span></p>
<p><b>Last Name:</b> <span id="lName"></span></p>

<script>
    $(document).ready(function () {
        $("#fName").html("Elisabeth");
        $("#lName").html("Meuer");
    });
</script>

</body>
</html>

Selecting Elements by their Style

You can select elements based on a CSS style they share. To do this, in the double-quote of the jQuery object, pass the value of the style preceded by a period. This would be done as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
<script src="Scripts/jquery-3.3.1.js"></script>
<style type="text/css">
.centered   { text-align:  center;  }
</style>
</head>
<body>

<script type="text/javascript">
    $(document).ready(function () {
        $(".centered"). . .;
    });
</script>
</body>
</html>

In this case, all elements that use the same style would be selected.

A style you use for selection doesn't have to have been created. This means that you can use a style that doesn't exist in a style section or in a CSS document, as long as you had applied it to the intended tag. Here are examples:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Identification</title>
</head>
<body>
    <h1>Identification</h1>

    <form name="Identification">
        <table>
            <tr>
                <td><label for="fname">First Name:</label></td>
                <td><input type="text" id="fname" class="something" /></td>
            </tr>
            <tr>
                <td><label for="lname">Last Name:</label></td>
                <td><input type="text" id="lname" class="has-values" /></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><input type="button" id="getFullName"
                           value="Show Full Name" class="production" /></td>
            </tr>
            <tr>
                <td><label>Full Name</label></td>
                <td><span id="fullName" class="result"></span></td>
            </tr>
        </table>
    </form>

    <script src="Scripts/jquery-3.3.1.js"></script>

    <script type="text/javascript">
        $(document).ready(function () {
            $(".production").on("click", function () {
                var firstName = $(".something").val();
                var lastName = $(".has-values").val();

                $(".result").text("");
            });
        });
    </script>
</body>
</html>

If you had applied a combination of classes to an element, you can use any of the classes.

Selecting an Element or Some Elements by their Style

If you have many elements that use the same style, if you want to select only one of some of the elements, you need a way to include only the element(s) you want or to exclude the other(s). You have many options. If the concerned element(s) use(a) (a) different HTML tag(s), in the double-quote of the jQuery object, pass the value of the style preceded by a period and the name of the HTML tag. Here are examples:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
<script src="Scripts/jquery-3.3.1.js"></script>
<style type="text/css">
.centered   { text-align:  center;  }
.blue       { color:       #0058ff; }
.right      { text-align:  right;   }
</style>
</head>
<body>
<h1 id="topTitle" class="centered"></h1>
<h2 class="centered">Expectations</h2>

<p class="centered"></p>
<p class="right">What was not supposed to happen happened.</p>

<script type="text/javascript">
    $(document).ready(function () {
        $("h2.centered").mouseenter(function (event) {
            $("h1.centered").html("Diagnostic Classifications");
            $("p.centered").html("What was supposed to happen happened.");
        });
    });
</script>
</body>
</html>

Getting an Element by Position

If you have many elements with the same HTML tag name in a webpage and if you make a selection by their HTML tag names or a style they share, you will get an array (namely a collection) of elements. To let you access the elements by their positions, the jQuery object is equipped with a method named get. This method takes as argument the index of the element you want to access.

Adding a Style

You can apply a style to an element that already has a style. To support this, the jQuery object is equipped with a method named addClass. To use this method, attach it to a selected item. The method is overloaded with two versions. One of the versions takes the new style as a string argument. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Argument</title>
<script src="Scripts/jquery-3.3.1.js"></script>
<style type="text/css">
.phrase { font-size:   18px;
          font-family: Garamond, Georgia, 'Times New Roman', serif; }
.high   { color:       blue;
          text-align:  center; }
</style>
</head>
<body>
<p id="argument" class="phrase">Absence of evidence is not evidence of absence</p>

<script type="text/javascript">
    $(document).ready(function () {
        $("#argument").addClass("high");
    });
</script>
</body>
</html>

Compounding Styles

To add more than one style, pass their names in the same argument but separate them with empty spaces.

The other version of the $().addClass() takes a function as argument.

Performing Operations on a Selection

Introduction

The selection is the main way you create an object from an HTML element in jQuery. After making such a selection, you get a fully functional object on which you can perform various types of operations.

Generally Appending a Value or Object to an Element

Appending an item consists of adding a value or an object at the end of an existing one. To support this operation, the jQuery object is equipped with an overloaded method named append. One of the versions of this method takes one required and one optional arguments. Its syntax is:

append(content [, content]);

The required argument can be a string that holds text to be added to the right side of the selected item that called the function. Here are examples:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Identification</title>
</head>
<body>
    <h1>Identification</h1>

    <form name="Identification">
        <table>
            <tr>
                <td><label for="fname">First Name:</label></td>
                <td><input type="text" id="fname" class="something" /></td>
            </tr>
            <tr>
                <td><label for="lname">Last Name:</label></td>
                <td><input type="text" id="lname" class="has-values" /></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><input type="button" id="getFullName"
                           value="Show Full Name" class="production" /></td>
            </tr>
            <tr>
                <td><label>Full Name</label></td>
                <td><span id="fullName" class="result"></span></td>
            </tr>
        </table>
    </form>

    <script src="Scripts/jquery-3.3.1.js"></script>

    <script type="text/javascript">
        $(document).ready(function () {
            $(".production").on("click", function () {
                var firstName = $(".something").val();
                var lastName = $(".has-values").val();

                $(".result").append(firstName);
                $(".result").append(" ");
                $(".result").append(lastName);
            });
        });
    </script>
</body>
</html>

Here is an example of using the webpage:

jQuery Selections

jQuery Selections

jQuery Selections

When the $().append() method has been called, it produces a jQuery object. As a result, you can call the method on that new object. Here are examples:

<script type="text/javascript">
     $(document).ready(function () {
        $(".production").on("click", function () {
            var firstName = $(".something").val();
            var lastName = $(".has-values").val();

            $(".result").append(firstName).append(" ").append(lastName);
        });
    });
</script>

As an alternative, if you want to add more items, pass as many arguments as you want to the method. Here is an example:

<script type="text/javascript">
     $(document).ready(function () {
        $(".production").on("click", function () {
            var firstName = $(".something").val();
            var lastName = $(".has-values").val();

            $(".result").append(firstName, " ", lastName);
        });
    });
</script>

The other version of the append() method uses the following syntax:

append(function);

This version takes a function as argument. The function must return the string that will be added to the element that called the append() method.

Appending to a Matching Element

To let you work in reverse of the append() nethod, the jQuery object provides a method named appendTo. Its syntax is:

appendTo(target)

This method works with the same goal as the append() method except that, while the append() method is called by the element that must be modified, the append() method is called by the string or format that must be applied to the element passed as argument. The appendTo() method takes a string as argument. The argument can contain the HTML tag name of an element, the identifier of an element, the style applied to an element, etc. In other words, the argument must specify a way to find one or more elements on the webpage. If such an element is found, the selected value or formatting that called it would be applied to the found element.

Prepending a Value or Object

To let you add a value or object before an element, the jQuery object is equipped with an overloaded method named prepend. One version of the prepend method takes one required and one optional arguments. Its syntax is:

preppend(content [, content]);

You can pass a single argument that is a string containing the value or the format to position before the selection that called this method.

Practical LearningPractical Learning: Ending the Lesson


Next Copyright © 2017-2022, FunctionX Next