jQuery DOM Manipulation Methods

jQuery DOM Manipulation Methods with Examples

In this article, I am going to discuss jQuery DOM Manipulation Methods with Examples. Please read our previous article, where we discussed How to Convert JSON Object to String and String to JSON Object. At the end of this article, you will understand everything about jQuery DOM Manipulation Methods.

jQuery DOM Manipulation Methods

jQuery provides methods to manipulate DOM in an efficient way. We do not need to write big code to modify the value of any element’s attribute or to extract HTML code from a paragraph or division.

A few of them simply change one of the attributes of an element, while others set an element’s style properties. Still, others modify entire elements (or groups of elements) themselves inserting, copying, removing, and so on. All of these methods are referred to as “setters,” as they change the values of properties.

A few of these methods such as .attr(), .html(), and .val() also act as “getters,” retrieving information from DOM elements for later use. All these methods are listed below.

  1. .addClass(): Adds the specified class(es) to each element in the set of matched elements..
  2. .after(): Insert content, specified by the parameter, after each element in the set of matched elements.
  3. .append(): Insert content, specified by the parameter, to the end of each element in the set of matched elements.
  4. .appendTo(): Insert every element in the set of matched elements to the end of the target.
  5. .attr(): 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.
  6. .before(): Insert content, specified by the parameter, before each element in the set of matched elements.
  7. .clone(): Create a deep copy of the set of matched elements
  8. .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.
  9. .detach(): Remove the set of matched elements from the DOM.
  10. .empty(): Remove all child nodes of the set of matched elements from the DOM.
  11. .hasClass(): Determine whether any of the matched elements are assigned the given class
  12. .height(): Get the current computed height for the first element in the set of matched elements or set the height of every matched element.
  13. .html(): Get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.
  14. .innerHeight(): Get the current computed inner height (including padding but not the border) for the first element in the set of matched elements or set the inner height of every matched element.
  15. .innerWidth(): Get the current computed inner width (including padding but not the border) for the first element in the set of matched elements or set the inner width of every matched element.
  16. .insertAfter(): Insert every element in the set of matched elements after the target.
  17. .insertBefore(): Insert every element in the set of matched elements before the target.
  18. Jquery.cssNumber: An object containing all CSS properties that may be used without a unit. The .css() method uses this object to see if it may append px to unitless values..
  19. Jquery.htmlPrefilter: Modify and filter HTML strings passed through jQuery manipulation methods.
  20. .offset(): Get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document.
  21. .outerHeight(): Get the current computed outer height (including padding, border, and optionally margin) for the first element in the set of matched elements or set the outer height of every matched element.
  22. .outerWidth(): Get the current computed outer width (including padding, border, and optionally margin) for the first element in the set of matched elements or set the outer width of every matched element.
  23. .position(): Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.
  24. .prepend(): Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.
  25. .prependTo(): Insert every element in the set of matched elements to the beginning of the target.
  26. .prop(): Get the value of a property for the first element in the set of matched elements or set one or more properties for every matched element.
  27. .remove(): Remove the set of matched elements from the DOM.
  28. .removeAttr(): Remove an attribute from each element in the set of matched elements.
  29. .removeClass(): Remove a single class, multiple classes, or all classes from each element in the set of matched elements.
  30. .removeProp(): Remove a property for the set of matched elements.
  31. .replaceAll(): Replace each target element with the set of matched elements.
  32. .replaceWith(): Replace each element in the set of matched elements with the provided new content and return the set of elements that were removed.
  33. .scrollLeft(): Get the current horizontal position of the scroll bar for the first element in the set of matched elements or set the horizontal position of the scroll bar for every matched element.
  34. .scrollTop(): Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element.
  35. .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.
  36. .toggleClass(): Add or remove one or more classes from each element in the set of matched elements, depending on either the class’s presence or the value of the state argument.
  37. .unwrap(): Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.
  38. .val(): Get the current value of the first element in the set of matched elements or set the value of every matched element.
  39. .width(): Get the current computed width for the first element in the set of matched elements or set the width of every matched element.
  40. .wrap(): Wrap an HTML structure around each element in the set of matched elements.
  41. .wrapAll(): Wrap an HTML structure around all elements in the set of matched elements.
  42. .wrapInner(): Wrap an HTML structure around the content of each element in the set of matched elements.

Reference: https://api.jquery.com/category/manipulation/

Note: In our previous examples, we have used many of these methods such val(), text(), html()….. In the upcoming articles, we will discuss all of these DOM manipulation methods. In this article, let’s pick the attr() method.

jQuery attr() Method

The attr() method sets or returns attributes and values of the selected elements. It can be used as both getter and setter. When this method is used to return the attribute value, it returns the value of the FIRST matched element. When this method is used to set attribute values, it sets one or more attribute/value pairs for the set of matched elements.

Syntax:

Example: jQuery DOM Manipulation Methods

In the below example, we want to return the ‘title’ attribute values of the div elements. But notice that by $(‘div’).attr() method, we are getting only the 1st attribute value of the matching set of elements

<!DOCTYPE html>
<html>
<head>
    <title>jQuery DOM Manipulation</title>
</head>
<body>
  <h3>jQuery DOM Manipulation</h3>
  <section>
    <div title="div1">
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim veritatis ab fugiat ducimus, totam ratione
      quod
    </div>
    <div title="div2">
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim veritatis ab fugiat ducimus, totam ratione
      quod
    </div>
    <div title="div3">
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim veritatis ab fugiat ducimus, totam ratione
      quod
    </div>
  </section>
  </br>
  <button class="demo">Click Me</button>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
    $(document).ready(function () {
    $('.demo').click(function () {
      console.log($('div').attr('title'));
    })
  })
  </script>
</body>
</html>

Now, run the above code and open the browser developer tool by pressing the F12 key and then click on the Click Me button you will see that, it will only log the title of the first div element title as shown in the below image.

jQuery DOM Manipulation Methods

To get all the title attribute values we have to iterate over the div elements. To do so, modify the Script section as shown below.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
  $(document).ready(function () {
    $('.demo').click(function () {
      $('div').each(function () {
        console.log($(this).attr('title'))
      })
    })
  })
</script>

With the above changes in place, run the code and open the browser developer tool by pressing the F12 key and then click on the Click Me button you will see that, now it logs all the three div elements title in the Console as shown in the below image.

jQuery DOM Manipulation Methods with Examples

Example: Setting Attribute Value using Attr method

In the below example, the attr() method is implicitly iterating over the matching div elements and setting the title attribute values to ‘mySampleDiv’. Notice that, if you hover on any of the div elements you will see the title ‘mySampleDiv’.

<!DOCTYPE html>
<html>
<head>
    <title>jQuery DOM Manipulation</title>
</head>
<body>
  <h3>jQuery DOM Manipulation</h3>
  <section>
    <div title="div1">
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim veritatis ab fugiat ducimus, totam ratione
      quod
    </div>
    <div title="div2">
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim veritatis ab fugiat ducimus, totam ratione
      quod
    </div>
    <div title="div3">
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim veritatis ab fugiat ducimus, totam ratione
      quod
    </div>
  </section>
  </br>
  <button class="demo">Click Me</button>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
    $(document).ready(function () {
      $('.demo').click(function () {
        $('div').attr('title','mySampleDiv')
        });
    });
  </script>
</body>
</html>

Now run the above code. Then click on the Click Me button and then mouse over on any of the div elements and you will see that the title attribute is changed to ‘mySampleDiv’ as shown in the below example.

Setting Attribute Value using Attr method

Example: Setting Attribute Value using Callback function in jQuery

In the below example, we will use the callback function to set the title attribute value.

<!DOCTYPE html>
<html>
<head>
    <title>jQuery DOM Manipulation</title>
</head>
<body>
  <h3>jQuery DOM Manipulation</h3>
  <section>
    <div title="sampleDiv">
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim veritatis ab fugiat ducimus, totam ratione
      quod
    </div>
    <div title="sampleDiv">
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim veritatis ab fugiat ducimus, totam ratione
      quod
    </div>
    <div title="sampleDiv">
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim veritatis ab fugiat ducimus, totam ratione
      quod
    </div>
  </section>
  </br>
  <button class="demo">Click Me</button>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
    $(document).ready(function () {
      $('div').attr('title', function (index, prevVal) {
        return prevVal + index;
      });
    });
  </script>
</body>
</html>

Notice carefully in the above example. Here we are using callback in attr() method. The function takes two parameters

  1. index of the element currently iterating over
  2. the previous value of the title attribute.

We are concatenating index no with the previous value of the attribute. Now, run the above code and then click on the Click Me button and then check the div element title attribute as shown in the below image.

Setting Attribute Value using Callback function in jQuery

Example: Setting Multiple Attribute Values using jQuery Attr DOM Manipulation Method

In this example, we will see that how to set the multiple attribute values.

<!DOCTYPE html>
<html>
<head>
    <title>jQuery DOM Manipulation</title>
</head>
<body>
  <h3>jQuery DOM Manipulation</h3>
  <section>
    <div title="sampleDiv1">
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim veritatis ab fugiat ducimus, totam ratione
      quod
    </div>
    <div title="sampleDiv2">
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim veritatis ab fugiat ducimus, totam ratione
      quod
    </div>
    <div title="sampleDiv3">
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim veritatis ab fugiat ducimus, totam ratione
      quod
    </div>
  </section>
  </br>
  <button class="demo">Click Me</button>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
    $(document).ready(function () {
      $('div').attr({
        'title': 'MyDiv',
        'style': 'border:2px solid black; background-color: skyblue; border-radius: 30px ',
      });
    });
    $('.demo').click(function () {
      $('div').each(function () {
        console.log($(this).attr('title'));
      });
    });
  </script>
</body>
</html>

In the case of setting multiple attribute values, you have to pass it as a JSON object. In this example, we are setting the title as well as the style attribute value. Notice that our style of the div elements has been changed and the title attribute value is also changed which is printed on the console.

Setting Multiple Attribute Values using jQuery Attr DOM Manipulation Method

Example: Remove an attribute using jQuery removeAttr() method

To remove an attribute, we need to use the removeAttr function. In the below example, we remove the title attribute from all the div elements.

<!DOCTYPE html>
<html>
<head>
    <title>jQuery DOM Manipulation</title>
</head>
<body>
  <h3>jQuery DOM Manipulation</h3>
  <section>
    <div title="div1">
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim veritatis ab fugiat ducimus, totam ratione
      quod
    </div>
    <div title="div2">
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim veritatis ab fugiat ducimus, totam ratione
      quod
    </div>
    <div title="div3">
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim veritatis ab fugiat ducimus, totam ratione
      quod
    </div>
  </section>
  </br>
  <button class="demo">Click Me</button>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
    $(document).ready(function () {
      $('.demo').click(function () {
        $('div').each(function () {
          $(this).removeAttr('title');
        })
      })
    })
  </script>
</body>
</html>

In the next article, I am going to discuss jQuery Wrap and UnWrap Elements with Examples. Here, in this article, I try to explain jQuery DOM Manipulation Methods with Examples and I hope you enjoy this Converting jQuery DOM Manipulation Methods article.

Leave a Reply

Your email address will not be published.