Menu Search Sign up

Call JQuery Method to Manipulate HTML DOM Elements

JQuery contains powerful methods such as text(), html(), and val() for getting HTML DOM elements and attributes.

You can also use text(), html(), and val() to set HTML DOM elements and attributes.

JQuery also makes it easy to add new elements/content, with the following methods:

  • 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

And of course, with JQuery, you can easily remove elements/content:

  • remove() - Removes the selected element (and its child elements)
  • empty() - Removes the child elements from the selected element

Three useful jQuery methods can be used for traversing up the DOM tree:

  • parent()
  • parents()
  • parentsUntil()

Two useful jQuery methods can be used for traversing down the DOM tree:

  •  children()
  •  find()

Multiple useful jQuery methods can be used for traversing sideways in the DOM tree:

  •     siblings()
  •     next()
  •     nextAll()
  •     nextUntil()
  •     prev()
  •     prevAll()
  •     prevUntil()

The first() method returns the first element of the selected elements.

The last() method returns the last element of the selected elements.

The eq() method returns an element with a specific index number of the selected elements.

The filter() method lets you specify a criteria. Elements that do not match the criteria are removed from the selection, and those that match will be returned.

Now let's take a look at an example:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("p").mouseover(function(){
    alert($("div p").last().text());
    $("div p").first().text("Changed Value!");
  });

});
</script>
</head>
<body>

<h1>Welcome to My Homepage</h1>
<div>
<p>This is a paragraph in a div.</p>
</div>

<div>
<p>This is a paragraph in another div.</p>
</div>

In the above example, when the user moves his mouse over the "div p" texts, the JQuery mouseover event will be fired, which will call the custom code to do 2 things: the first is to display the last "div p" text in the alert window; and the second is to change the first "div p" text into "Changed Value!".