Manipulating DOM in WordPress using JQuery

Thanks to WordPress’ open-source platform and vibrant developer community, creating themes for the platform has a pretty wide appeal. Navigating all the elements and content required to build a WordPress site can be challenging, however, depending on your programming knowledge and experience.

Fortunately, the Document Object Model (DOM) can make it easier to manipulate or travel through a site’s HTML code. The DOM works by enabling you to create a tree made up of various nodes or objects. This opens up the opportunity to change the display, structure, or function of the site, using JavaScript libraries such as jQuery.

In this article, we’ll explain what the DOM is and why you might want to use it. We’ll then provide some standard jQuery manipulation techniques for using the DOM with WordPress. Let’s dive right in!

What Is the DOM?

Simply put, the DOM is an Application Programming Interface (API) for HTML. It creates a tree of objects that represents the content and structure of a web page. It’s also a platform and language-agnostic script, which makes it quite versatile. When the DOM represents HTML source code in this way, it makes it accessible so that various programming languages can connect to it.

Why Use the DOM?

As a WordPress user, you are likely seeing the DOM in action any time you encounter dynamic interactivity. This might include when an error is returned if a form is submitted with missing information. Content sliders are another example of the DOM in use:

Developers can use the DOM to update and change nearly all of the elements on a web page. You can use it to build documents and navigate their structure. The DOM can also be used to add, modify, or delete elements and objects. 

DOM Manipulation With JQuery

To be clear, the DOM and HTML are not the same, although they should contain the same elements. The DOM is a modeled representation of HTML source code, and can be altered by client-side JavaScript.

Below, we’ll be looking at methods in the jQuery library for testing out some DOM manipulation techniques. Keep in mind that different browsers handle the DOM in their own way, but you don’t have to do anything special to begin using it. All browsers use some form of the DOM to make pages accessible to JavaScript.

DOM Manipulation Techniques

The DOM can be used in a wide variety of ways. To illustrate its flexibility, let’s look at six techniques that can get you started with this useful API.

1. The Before() Method

True to its name, the before() method is used when you want to insert any element before another target element, as indicated in the code.

In this example, the method can be used to add a square element with text above a designated element, such as a button, once it is clicked on:

$(this).before( "<div class='square'>Another square</div>" );

Page placement and layout are considerations to keep in mind when using this method. You’ll want to make sure your new element is not going to break your layout or cause trouble visually.

2. The After() Method

In the same way that the before() method lets you insert elements before another indicated element, the after() method allows for the opposite. For example, it could be used to add an element right below a button, once the button is selected: 

$(this).after( "<div class='square'>Another square</div>" );

Adding interactive content by manipulating the DOM with jQuery like this is a solid way to gain interactivity, without losing speed in the process.

3. The Append() Method

Instead of making individual new elements appear, you might want to add your new element onto an existing one. For instance, maybe you want to add the text “Happy Birthday!” within a colored area whenever a specific button is clicked on.

To append your new element to the target element’s existing content, you would insert the append() jQuery command within the HTML source code:

$( ".box" ).append( "<p>Happy Birthday!</p>" );

This method adds the manipulation onto the end of the element you indicate in the string, rather than putting it before or after. Within the context of the full HTML document, you can see how the manipulation takes place:

<!doctype html>
<title>Example</title>
<style>
.box {
  background: orange;
  color: white;
  color: white;
  width: 150px;
  padding: 20px;
  margin: 10px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
  $( function() {
    $( "button" ).click( function() {
      $(this).after( "<div class='box'>Happy Birthday!</div>" );
    });
  });
</script>
<button>Create a box</button>

This technique gives you a simple option for creating interactivity within a confined space. Just remember, with this particular method the manipulations will appear as an extension of the element you indicate, rather than as new individual elements.

4. The Prepend() Method

As the balance to the append() method, prepend() will add an element to the end of whatever target element you indicate in the jQuery command:

$( ".banner" ).prepend( "<p>Happy Birthday!</p>" );

In this example, the text “Happy Birthday!” would appear at the beginning of the banner indicated in the code string.

It’s worth noting that these methods (including before(), after(), and append()) are all acceptable approaches for simple uses. However, we do recommend other techniques for more complex insertions.

5. The Clone() Method

Next up, the clone() method is a pretty powerful option in terms of manipulating the DOM with jQuery. While the previous four techniques enable you to insert elements and move them around, clone() makes it possible to copy an element, remove it from its original place, and reinsert or append it elsewhere.

For example, this line means that the original box element will remain where it is, while a clone of it will be appended to the triangle element:

$( ".box" ).clone().appendTo( ".triangle" );

The downside to this method is that it can cause duplication of the element’s id attribute. These attributes are meant to be unique. You can avoid this issue by using the class attributes as identifiers, and employing the clone method sparingly

6. The Wrap() Method

Finally, the wrap() method is useful if you want to wrap an element around an existing string. For instance, you can wrap several paragraphs in a new HTML structure by identifying the class and indicating what structure is being implemented:

$( ".targetclass" ).wrap( "<div class='new'></div>" );

With this technique, you are creating a <div> around any element that matches the target class in the wrap() string. While you can create a wrap that is several levels deep, however, you should make sure there is only one innermost element.

Troubleshooting the DOM

When it comes to working with the DOM, we want to highlight one key aspect you’ll want to pay attention to. In order to keep your pages loading fast and avoid unnecessary code (especially if you’re developing a theme), you should be mindful not to use any elements that are not part of the DOM tree.

If you’re not sure whether an element is part of the DOM or not, you can check each one through your browser on the front end of your site. You can inspect elements on the page, and determine where they are included in the DOM tree.

This is especially helpful when another script has changed the original HTML of your site. Otherwise, your HTML and DOM may sometimes appear exactly the same. 

Explore Other WP Engine Resources and Tools

If you think of the DOM as an organic part of your site, a living resource that responds to HTML source code, the power of its accessibility is pretty astounding. That’s why understanding the DOM and how it can be used to enhance your projects can help take your site to the next level. 

Manipulating the DOM with jQuery highlights the beauty of WordPress’ open-source platform. Here at WP Engine, we understand how high-quality developer resources can make all the difference. That’s why we offer plenty of help for WordPres users, along with top-notch hosting plans!

Get started.

Build faster, protect your brand, and grow your business with a WordPress platform built to power remarkable online experiences.