How to Manipulate The Page in jQuery

We've mentioned the document object model (DOM) before. It's the model that represents page elements in an HTML document. It's what you use the reference any element whether it's in jQuery, HTML, CSS or any other language. Before you can start referencing elements, you need to understand the DOM and what you can do to manipulate different elements throughout the page. This article describes the DOM and different configurable elements throughout a page.

DOM Introduction

The DOM represents every element in your web page except for text. It's a structured object model that gives you the ability to reference elements in your page. Take a look at the following HTML.

<div id="div1"></div>

<div id="div2"></div>

<input type="text" id="frmInput" value="Form Input" />

In the HTML above, there are three elements in the DOM object. Of course, you also have the opening and closing HTML tags, the body tag and the head tag in a standard HTML page. The above code is something you could have in a standard web page. You have two div containers named div1 and div2. Then, we have an input text box. Normally, the input text box would be a part of a parent form element, which makes it a child element. However, we just used an input text box to illustrate the object model.

If you want to reference these three elements, you use selectors. The following jQuery code manipulates all three elements included in the above HTML code.

<script type="text/javascript">



        $("#div1").text("This function places text in the container.");

        $("#div2").html("<b><i>This function inserts HTML into the container.</i></b>");

        $("#frmInput").val("This function inserts a value into a form text box.");});


In all three of these statements, jQuery methods manipulate an attribute or a property for an element. The div1 container has text inserted using the "text" method. This method only inserts plain text without any HTML formatting.

The second statement inserts HTML into the div2 container. Notice that it has HTML formatting included. This method inserts HTML and text, so your content is also formatted using HTML tags. Both the text and html methods are covered more in the next chapter.

The final statement uses the "val" method. This method is used to insert values into form elements. The val method can be used to set a default value or a value based on user input.

These three methods are used to do basic manipulations of the DOM. You'll need to know these basic methods and queries to work with any page in jQuery.

Get and Set Attributes

Another common procedure you will find in web design projects is changing attributes based on user input. The "attr" method is used to change attributes in an object such as a link element. Remember that every HTML element is a part of the DOM, and you can query for the specific element using a jQuery selector. We already showed you how to use selectors, but it's important to use the right one to grab the right object on the page.

For a link element, you can reference it using either a class selector, a type selector or an ID selector. The most common way to reference a link object is to use a class or ID selector since you usually have more than one link on a page. Remember that using the type selector references all elements of that type on the page, but the ID selector narrows down your query to just one element.

For instance, suppose you want to change a link element's href property. You can use jQuery to dynamically edit the link. First, you need a link in your HTML page. We'll use the following link object.

<a href="" id="link" class=".linkclass">Click Here!</a>

The above link points to Google's home page. We don't have anything special to configure the link, but we can use the following jQuery code to change the link href.




        $("#link").attr("href", "");



The above function uses the link's ID specifier to change the link's URL. Notice that the first parameter is the "href" property. The second parameter is the "" URL. These attributes are changed when the function is called.

Get and Set Classes

With CSS, you set classes for specific elements in the DOM. You can also add and remove classes using jQuery. You can also retrieve the current classes for an element using the "css" method.

Let's say you have a CSS class where you set the font style to bold, but you want to dynamically change the color to red based on input from the user. You can dynamically add a class in jQuery using the addClass method.

First, let's create two CSS classes for the web page text.

.bold {

    font-weight: bold;


.red {

    color: red;


Now let's create a button that can be used to add the class to some text.

<button>Click here to change the class</button>

<p class="bold">This is the text that will change</p>

The paragraph only has the "bold" class applied when the page loads. The following jQuery code changes the paragraph's text color.




The function adds the class "red" to the paragraph, so when the button is clicked the text changes to a red color.

You can also remove a class from the element using the removeClass method. The following code removes the "red" class from the element.




The removeClass removes the "red" class so the content is still bold formatted but the font's red color is removed.

Finally, you might want to get the CSS classes assigned to an element. With the css method, you can retrieve the value for a specific CSS property. You can also set a class property with the css method. The difference between the addClass method and the css method is that addClass method adds a new class to an element but the css method changes a specific property.

The following jQuery code changes the background color of the paragraph element to black.

$("p").css("background-color", "black");

Get and Set Form Values

You can get and set values in form elements using the val method. The val method is normally used with form text boxes, but you can also use it to work with other form elements. You'll mostly use it with text boxes, so we'll show you how to get and set text box values using jQuery.

You first need a form in your DOM. Unlike the other samples we've shown, you don't need any CSS classes for your form variables to use the val method. You just need form elements. The following HTML code is an example of a simple form text box that asks the user to input a first name value.

<input type="text" id="firstname" value="Enter a first name">

One common way you can use jQuery with form text boxes is to first identify the current value and then change it depending on the current value entered. For instance, you can use jQuery to identify if the text box is blank. If the text box has no value, then you can send an alert to the user that a value must be entered before the form can be submitted.

The following jQuery code retrieves the value from the "firstname" text box.

var value = $( "#firstname" ).val();

We set a default value for the text box, which is "Enter a first name." If the user enters no value in the text box, the variable "value" contains the value "Enter a first name." The jQuery framework is built on JavaScript, so you can use JavaScript syntax in jQuery. If you wanted to know if a user had entered a value, you use the "if" statement to check if the initial content is in the text box.

You can set a value for the text box using the val method. The following jQuery code assigns a value to the same "firstname" form value.

$( "#firstname" ).val("Joe Smith");

The code above sets "Joe Smith" to the firstname's text value.

Get and Set Text

The "text" method in jQuery sets or gets the text within a set of tags. The tags can be any element such as a paragraph (p) or a div container (div). The text is only plain text and no HTML is considered. If you want to work with HTML markup, you need to use the html method. The text method is good when you need to dynamically set text based on user input.

First, you need an HTML element to work with. We'll work with the following paragraph tag to dynamically set text content.

<p> This is the initial content for the paragraph. </p>

You can get and set text within an element with the text method. The following jQuery code retrieves the text within the paragraph tag.

var text = $( "p" ).text( );

In the above code, the "text" variable contains the text "This is the initial content for the paragraph." You can also set the text with jQuery. The following jQuery code sets the text for the paragraph tag.

$( "p" ).text( "This is new text for the paragraph." );

In the above code, instead of returning a text value, the jQuery code sets the text for a paragraph. In this example, the paragraph now contains the text "This is new text for the paragraph." You can set this code to run when the page loads or when a user clicks a button. You can also set the text to change after a user enters specific input. This is the advantage of jQuery. You can completely change the way the page interacts with the user based on input.

Get and Set HTML5 Data

HTML5 introduced the concept of data attributes. Any attribute within an HTML element that starts with the prefix "data-" is considered a data attribute. The "data-" prefix can be followed by any name. The name is what distinguishes the data attribute from the others. You can have one or several data attributes in an element. Not only can you save a static data value, you can also store arrays and object values in a data attribute. It's one of the most important attributes for client-side scripting and dynamic coding.

The jQuery "data" method works with this data attribute. You can set a data attribute's value or retrieve it using the "data" method. The following HTML5 code is an example of a paragraph tag with several data tags.







The above article tag has an id of "tutorial" and three data columns that define the attributes for the tag. This information is added extras you can use in your application. All three of the data attributes are customized "fields" that help you dynamically work with your web page elements based on user input. You can set or retrieve these attribute values using jQuery's "data" method.

It's common to retrieve data values using jQuery. The following code retrieves and displays the value in the "parent" data attribute.


var data = $( "#tutorial" ).data( "parent" );

alert (data);


The above code assigns the value of the parent data attribute to the variable named data. Then, the alert function displays it to the user. Normally, you retrieve the data and use it to manipulate elements in your web page.

You can also change data values using jQuery. The following code edits the parent attribute's value.


$( "#tutorial" ).data( "parent", "JavaScript" );


The above code changes the value to "JavaScript."

Get and Set Positions

When you build your pages, each element is contained within a parent element. It's also contained within the DOM. When you work with positioning, this distinction is important to properly define where a child element should display. All positioning on a page is relative to its container including the DOM, and jQuery has two methods to handle this procedure. The "position" method retrieves and sets the location of an element based on the parent. The "offset" method retrieves the location relative to the document.

Let's create HTML code that has a parent div container with a paragraph child element.

<div><p>This is a container</p></div>

Suppose we want to get the location of the paragraph element relative to the document. We use the position method. The following code gets and then sets the position of the paragraph element.

var p = $( "p" ).position();

p.text( "left position: " + p.left + " right position: " + p.right);

$("p").css({top: 20, left: 20, position:'relative'});

In the code above, the first two lines get the position of the text. Then, we set the paragraph's position relative to the parent. Notice that we used the "css" method to change the position of the paragraph.

You can also use the offset method, but remember that the offset method is relative to the document. The following jQuery code sets the paragraphs position using the offset method.


$( "p" ).offset({ top: 10, left: 10 });


Notice that the offset method can be used directly to set the location of the paragraph element. Since the position is relative to the document, this command sets the position to the top left corner of the document.

Once you understand how to manipulate HTML elements, you'll fully see where jQuery can be useful in your client-side scripting. You'll also understand why it's the go-to language for so many programmers who work with website design and coding.