Learn How to Create an Element in jQuery

Creating a new element is one of the most basic tasks you can accomplish with the jQuery JavaScript library. Using jQuery, the task is a lot simpler than the equivalent approach with the Document Object Model (DOM). You’ll also find it more flexible and expressive, the more you use jQuery.

To serve a purpose, you’ll need to be able to add your element to a web page. Learn how to add a new list item or replace a paragraph with new content using jQuery.

What Is jQuery?

The jQuery library is a collection of JavaScript code with two primary aims:

  • It simplifies common JavaScript operations.
  • It handles cross-compatibility JavaScript issues between various browsers.

The second aim caters for bugs, but it also addresses implementation differences between browsers. Both aims are less necessary than they used to be, as browsers improve over time. But jQuery can still be a valuable tool.

What Is an Element?

An element is sometimes referred to as a tag. Although the two are often used interchangeably, there’s a subtle difference. A tag refers to the literal

 or

 you include in an HTML file to markup the text content. An element is the behind-the-scenes object that represents the marked-up text. Think of an element as the DOM counterpart to the HTML tags.

How to Create a New Element Using jQuery

Like most jQuery operations, creating an element starts with the dollar function, $(). This is a shortcut to the core jQuery() function. This function has three distinct purposes, it:

  • Matches elements, usually ones that already exist in the document
  • Creates new elements
  • Runs a callback function when the DOM is ready

When you pass a string containing HTML as the first parameter, this function will create a new element:

$("")

This returns a special jQuery object which contains a collection of elements. In this case, there’s a single object representing an “a” element which we just created.

The string must look like HTML to distinguish this action from matching elements. In practice, this means the string must begin with a . You cannot add plain text to the document using this method.

It’s important to understand that this doesn’t add the element to your document, it only creates a new element ready for you to add. The element is ‘unattached’, taking up memory but not actually part of the final page—yet.

Adding More Complex HTML

The dollar function can actually create more than one element. In fact, it can build any tree of HTML elements you want:

$("
  • one
  • two
  • three
")

You can also use this format to create an element with attributes:

$('')

How to Set Attributes on a New Element

You can create a new jQuery element and set its attributes without having to build the full HTML string yourself. This is useful if you’re generating attribute values dynamically. For example:

photo = new Date().getHours() > 12 ? "afternoon.jpg" : "morning.jpg";
$("", { src: photo });

How to Add an Element

Once you’ve created a new element, you can add it to the document in several different ways. The jQuery documentation gathers these methods together under the ‘manipulation’ category.

Add as the Child of an Existing Element

$("body").append($("

Hello, world

"));
$(document.body).append($el);

You can use this method, for example, to add a new list item at the end of a list.

Add It as the Sibling of an Existing Element

$("p.last").after("

A new paragraph

")
$("ul li:first").before("
  • new item
  • ")

    This is a good choice if, for example, you want to add a new paragraph in the middle of two others.

    Replace an Existing Element

    You can swap an existing element for a newly-created one using the replaceWith() method:

    $('#old').replaceWith("

    New paragraph

    ");

    Wrap Around an Existing Element

    This is quite a rare use case, but you might want to enclose an existing element in a new one. For example, you might have a code element that you want to wrap in a pre:

    $('code#n1').wrap("
    ")

    Accessing the Element You’ve Created

    The $() function returns a jQuery object. This is useful for follow-up operations:

    $el = $("p");
    $('body').append($el);

    Note that, by convention, jQuery programmers often name jQuery variables with a leading dollar sign. This is simply a naming scheme and is not directly related to the $() function.

    Creating Elements Using jQuery

    Although you can manipulate the DOM using native JavaScript functions, jQuery makes it much easier to do so. It’s still very useful to have a good understanding of the DOM, but jQuery makes working with it a lot more pleasant.

    Source: makeuseof.com

    Related posts

    How to Turn Off Instagram Read Receipts

    Connections #336: Today’s Answer and Clues (Sunday, May 12, 2024)

    What are AI PCs, and What Makes Them Different?