jQuery tricks for DOM Manipulation

jQuery tricks for DOM Manipulation

In this article we will explore jQuery’s methods that help a web developer in their daily work.

1. Changing attributes with jQuery

We can change HTML DOM elements like Divs,  Lists, form elements etc ‘s attributes using jQuery very easily.

addClass                      

We can use add class to each set of matched element

This function can take a class name as .addClass(.className)

or can take a function .addClass(function()) -> String

As of jQuery 1.4, the .addClass() method’s argument can receive a function.

 parents([])

parentts function have brackets inside it. It means this function can take an argument but that is optional and can be omitted.

.toggleClass(className)

.append Method

Jquery’s .append element inserts content at the end of each element in the set of all matched elements.

We  use append method to append a new element at the end

 

.attr() method

Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.

We will get class attribute of paragraph element.

.before

Insert content, specified by the parameter, before each element in the set of matched elements.

We  use append method to append a new element at the end

And our HTML become as below.

.css()

Get the value of a computed style property for the first element in the set of matched elements or set one or more CSS properties for every matched element.

Now with CSS method we change its color.

This command will change color to red.

.html

Get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.

To change content of the container class we use .html method.

now HTML will become

.remove

Remove the set of matched elements from the DOM.

To remove the content  with class hello

So the HTML content becomes

.text

Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.

The code

will produce the following DOM output:

.val()

Get the current value of the first element in the set of matched elements or set the value of every matched element.

.wrap

Wrap an HTML structure around each element in the set of matched elements.

These are some JQuery methods for manipulating Dom.

In next article we will explore jQuery in depth.

Note:  with reference from http://jquery.com