Using jQuery, wrap two specific HTML elements together

I am working with a set of elements:

<div id="one">ONE</div>
<div id="two">TWO</div>
<div id="three">THREE</div>
<div id="four">FOUR</div>
<div id="five">FIVE</div>

My goal is to wrap a DIV tag around the elements with IDs "two" and "three" in order to achieve this structure:

<div id="one">ONE</div>
<div class="wrapped">
    <div id="two">TWO</div>
    <div id="three">THREE</div>
</div>
<div id="four">FOUR</div>
<div id="five">FIVE</div>

Although the "wrapAll" function can only target elements with the same class, like so:

$(document).ready(function(){
    $( "div" ).wrapAll( "<div class='wrapped' />");
});

I am hoping for a more elegant solution rather than having to assign the same class to the two DIVs before wrapping them using jQuery.

Answer №1

To achieve this, simply use the code snippet:

$('span#two, span#three').wrapAll('<div class="wrapper" />')

Example on jsbin

Answer №2

To select the two elements you desire, simply utilize the wrapAll() method.

According to the documentation (emphasis added by me):

The .wrapAll() function allows for any string or object that would typically be used with the $() function to define a DOM structure. This structure can be nested multiple levels deep, but should consist of only one innermost element. This structure will surround all the elements in the matched set of elements as a unified group.

Here is a link to the demonstration: https://jsfiddle.net/93dyokr0/1/

$('#two, #three').wrapAll( "<div class='wrapped' />");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason file inputs do not trigger 'input' events, while 'change' events do fire?

Trying out a basic input: <input type="file"/> Noticing that the input event doesn't trigger when a new file is selected: $('input').on('input', function(event){ console.log('input value changed', event.targe ...

Using jQuery to Decode the XML Document Containing National Threat Level Data

Recently, I've been experimenting with using jQuery to extract data from the DHS Threat Level found in their XML file. However, despite my efforts, I haven't been able to make it work. As a newcomer to Javascript and non-presentational jQuery, I& ...

Creating a new dynamic page can be achieved by clicking on a dynamically generated link. Would you like to learn how to do that?

Recently, I developed a custom API using Node.js to retrieve information about blogs from Medium.com. The API currently provides: The author/main picture of the article Title A link to the article on medium.com (redundant) The entire article text in the ...

I am facing an issue with grabbing text using simple HTML DOM in PHP with cURL

I have implemented the following code in my script to extract a specific part of the source code that I require, but I encountered this error: Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting ')' in /home/cyberhos/pub ...

What is the best way to apply filtering to my data source with checkboxes in Angular Material?

Struggling to apply datatable filtering by simply checking checkboxes. Single checkbox works fine, but handling multiple selections becomes a challenge. The lack of clarity in the Angular Material documentation on effective filtering with numerous element ...

Can you explain the purpose and functionality of this jQuery code snippet?

const elementsInBody = $("div", $("body")).length; This code snippet reminded me of something I saw in the qUnit documentation, and it's unlike anything I've encountered before. ...

Error message: "Maximum width header anomaly"

I've been working on a full-width header tumblr theme and everything looks great until I resize the screen to a smaller size, like on a mobile or tablet. The header ends up cutting off and no longer maintains its full width. You can see an example of ...

Explore the tree structure with AngularJS and populate it with data from a JSON

After utilizing the AngularJS TreeView example from this JSFiddle link, I encountered a peculiar issue. When attempting to retrieve data from a JSON file similar to the code provided, the tree structure appeared empty. Upon inspecting the $scope.roleList1 ...

How can the value of a button be displayed in an input box using an onclick function?

When the button '1' is clicked, it displays the value "1" inside a <!p> tag. However, the second button '2' does not display the value "2" in the input box. Even though both functions are identical. //Function with working func ...

Focusing on pinpointing certain mistakes within Drupal 7

When working with Drupal, encountering errors is a common issue. While some errors are simple to fix, others can be quite complex and require significant time and effort to resolve, even if the website appears to function normally despite the error. My qu ...

I need assistance setting up a Facebook page feed using Angular.js. I want to display the posts in a list of cards and include a fullscreen image gallery. Is

Hey there! I'm in the process of developing an app that pulls Facebook page posts and showcases them with custom CSS. The app is functioning smoothly with two controllers, DashCtrl and MainCtrl, each working fine on its own. However, when trying to tr ...

How do I create a new JSON Object with only two properties by selecting from an existing JSON Object with four properties?

Below is a JSON object example: [ {'car':'punto','brand':'fiat','color':'black','model':'2007'}, {'car':'XUV500','brand':&ap ...

My jQuery does not function correctly when I try to set a variable

Presented below is a crucial function: <script type='text/javascript'> $('#clicktogohome').live('click', function(){ history.pushState({}, '', this.href); popstate(this.href); return false; }); $('# ...

What are some ways I can enhance the typography within Material UI?

Currently, I am in the process of developing a custom theme utilizing createMuiTheme. However, my application requires more typography variants than what Material UI provides out of the box. I need to extend the typography so that it aligns with my specifi ...

Refreshing a <div> element in Django, yet there is no visible update

As I utilize a barcode scanner to add objects to my array list, the data is populated after each scan depending on the scanning speed of the user. To exhibit this data, I have designed a dedicated page. My intention is to avoid refreshing the entire page b ...

What is the best way to display JSON data in a Django template?

Looking to extract data from a URL in this format: http://www.example.com/data?format=json The output will resemble the following structure: student_details: { terms: { subjects: { assigments: { id:11, name:"ass_1 ...

Trigger Modal using PHP/JavaScript

After implementing the code below on my page, I expected guests to be redirected to the main page post login and greeted with a small pop-up modal containing a thank you message. However, despite trying multiple variations of this code, it doesn't see ...

Transforming dates from JSON and showcasing them on a DataTable

I'm facing an issue with my local JSON file where the dates are being rendered in a DataTable as /Date(1350028800000)/ (10/12/2012). I came across this thread which talks about converting the date format, but I need help figuring out how to implement ...

Designing a div with a proportional size amidst elements of fixed dimensions

I need help figuring out how to create a dynamically sized div based on the browser's height. I'm not sure where to start or how to approach this problem. The layout I have in mind includes a 50px high header, followed by the dynamic div and the ...

How to utilize the reduce method with an array of objects in JavaScript

Every week, a number of objects are delivered to me. Each object contains information such as date, hours, and other fields. I need to arrange these objects in an array based on the total hours for each day. Here is an example of the objects: var anArray ...