Placing a Div wrapper around the contents of two corresponding elements

I am currently attempting to wrap a div with the class name 'wrapped' around two other divs containing innerHTML of 'one' and 'two'.

<div class='blk'>one</div>
<div class='blk'>two</div>

My goal is to utilize the first and second 'clearfix' class element as selectors to wrap the contents between them with a parent div. After reviewing the code below, it seems that wrapAll will only wrap the matched elements. I am looking for a jQuery functionality that will allow me to wrap 'one' and 'two' with a parent div.

var arr = $('.clearfix');

$(arr[0], arr[1]).wrapAll('<div class="wrapped"/>');
.wrapped {
  background-color: 'red';
}

.hidden {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <div class='clearfix'></div>
  <div class='blk'>one</div>
  <div class='blk'>two</div>
  <div class='clearfix'></div>
  <div class='blk'>3</div>
  <div class='blk'>4</div>
  <div class='clearfix'></div>
</div>

The desired output should be as follows:

<div>
  <div class='clearfix'></div>
  <div class='wrapped'>
    <div class='blk'>one</div>
    <div class='blk'>two</div> 
  </div>
  <div class='clearfix'></div>
  <div class='blk'>3</div>
  <div class='blk'>4</div>
  <div class='clearfix'></div>
</div>

Answer №1

It seems like you're looking to wrap a div (with the class wrapped) around the two elements (with the class blk) that have the text content "one" and "two."

An effective way to do this would be using the :eq selector - which allows you to target specific elements for the .blk class selector (in this case, the first and second ones) and then apply the wrapping only to those:

/* Select the first and second elements that match the .blk selector
   and apply the wrapped div only to those */
$('.blk:eq(0), .blk:eq(1)').wrapAll('<div class="wrapped"/>');
.wrapped{
  background-color: red; /* Corrected syntax error here as well :) */
}
.hidden{
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
 <div class='clearfix'></div>
 <div class='blk'>one</div>
 <div class='blk'>two</div>
 <div class='clearfix'></div>
 <div class='blk'>3</div>
 <div class='blk'>4</div>
 <div class='clearfix'></div>
</div>

Answer №2

If you want to achieve this, consider using the .filter() method.

let elements = $('.blk');
elements.filter((index, element) => index < 2).wrapAll(`<div class="wrapped"></div>`);
.wrapped{
  background-color: blue;
}
.hidden{
  display: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
 <div class='clearfix'></div>
 <div class='blk'>one</div>
 <div class='blk'>two</div>
 <div class='clearfix'></div>
 <div class='blk'>3</div>
 <div class='blk'>4</div>
</div>

Answer №3

var clearfixParent = $('.clearfix').parent();

var wrappedEle = 0;
$(clearfixParent).find( 'div' ).each(function(){
 if( $(this).hasClass( 'clearfix' ) ) {
    wrappedEle += 1; 
    $(this).after('<div class="wrapped"/>');
 } else {
    $(this).appendTo( '.wrapped:eq(' + ( wrappedEle - 1 ) + ')' );
 }
});
.wrapped {
  background-color: 'red';
}

.hidden {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <div class='clearfix'></div>
  <div class='blk'>one</div>
  <div class='blk'>two</div>
  <div class='clearfix'></div>
  <div class='blk'>3</div>
  <div class='blk'>4</div>
  <div class='clearfix'></div>
</div>

Answer №4

Using the DOM API instead of jQuery is a great alternative for this task.

const appendSelectedSiblings = selector => target => {
  while (target.nextElementSibling && target.nextElementSibling.matches(selector)) 
    target.appendChild(target.nextElementSibling)
}

document.querySelectorAll('.clearfix').forEach(appendSelectedSiblings('.blk'))
.clearfix > .blk { background: green };
<div id="root">
  <div class='clearfix'></div>
  <div class='blk'>one</div>
  <div class='blk'>two</div>
  <div class='clearfix'></div>
  <div class='blk'>3</div>
  <div class='blk'>4</div>
  <div class='clearfix'></div>
</div>

Answer №5

Based on the markup provided, it seems like you want to group together all adjacent divs with class "BLKs".

I have created a dynamic snippet that can accomplish this task without the need to specify the index for wrapping.

Feel free to make any enhancements to the code for better efficiency.

var divs = $(".scan").find("div");
var toEnclose = [];
var continueEnclose;
var latestArray = [];

divs.each(function(i) {
  if ($(this).hasClass("clearfix")) {
    if (latestArray.length != 0) {
      toEnclose.push(latestArray);
      latestArray = [];
    }
  }
  if ($(this).hasClass("blk")) {
    latestArray.push(i);
  }
});

if (latestArray.length != 0) {
  toEnclose.push(latestArray);
  latestArray = [];
}

var enclose;
var mix = [];

$.each(toEnclose, function(i, k) {
  $.each($(this), function(i2, k2) {
    if (i != 0) {
      k2 += i;
    }
    mix.push(".scan div:eq(" + k2 + ")");
  });

  enclose = mix.join(",");
  // console.log(enclose);
  $(enclose).wrapAll($("<div class='wrapped'></div>"));
  mix = [];
});
.wrapped {
  background-color: red;
  margin-bottom: 5px;
}

.hidden {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="scan">
  <div class='clearfix'></div>
  <div class='blk'>one</div>
  <div class='blk'>two</div>
  <div class='clearfix'></div>
  <div class='blk'>3</div>
  <div class='blk'>4</div>
  <div class='clearfix'></div>
  <div class='blk'>5</div>
  <div class='blk'>6</div>
  <div class='blk'>7</div>
</div>

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

Encountering a problem when attempting to utilize AngularFire's Cloud Messaging Angular module due to missing configuration values for the app

Working with Firebase Cloud Messaging in my Angular application using AngularFire2 has presented a challenge. I am facing an error when attempting to retrieve the user's current token. I have already set up the "firebase-messaging-sw.js" and "manifes ...

Using the class for jQuery validation as opposed to the name attribute

I am looking to implement form validation using the jquery validate plugin, but I am facing an issue with using the 'name' attribute in the html since it is also used by the server application. Specifically, I want to restrict the number of check ...

"Prisma vs. Supabase: A Comparison of Image Uploading

I am encountering an issue with adding image URLs to the Prisma database. I have successfully uploaded multiple images from an input file to Supabase storage, but when I try to add their URLs to the database, I receive an error regarding property compatibi ...

Issues observed when implementing replaceWith() to replace text tags with input field on a web page

Just a simple EDIT request. I want to modify the headers so that when I click on the "edit" icon, the header will change to a text field and the "edit" icon will switch to a "save" icon. $('#editheader').click(function(e){ va ...

Tips for passing an object as an argument to a function with optional object properties in TypeScript

Consider a scenario where I have a function in my TypeScript API that interacts with a database. export const getClientByEmailOrId = async (data: { email: any, id: any }) => { return knex(tableName) .first() .modify((x: any) => { if ( ...

Sitelinks and a brief description appear beneath the website name when it is displayed in search

Is there a way to incorporate "metadata" (green and red lines in the image below) into a website? I might not have the correct term for it, so my apologies in advance. I attempted changing the following tag in the index.html file, but I am uncertain if thi ...

What is it about Next JS and React JS applications that causes them to use up so much cache?

"What causes Next.js and React.js applications to need a large cache, and how does this affect their performance and resource usage?" Refreshing constantly for even small changes in the application as a developer can be frustrating. Are there an ...

What is the best way to align text with my CSS number and circle on the same line?

Here are two questions for you: First off, I've successfully created a circle with a number inside it using CSS. How can I go about filling the circle with color? Secondly, I'd like to know how I can align the words "Opportunity #1" on the same ...

Tips for aligning 2 columns when both table cells contain inner tables

Concerning my HTML table, cells #3 and #4 contain inner tables. I am facing an issue with aligning the rows within each table in cell #3 and cell #4 properly. Sometimes, the length of text in a row exceeds a single line, causing misalignment with the othe ...

Implementing a JSON array to object conversion in an Express REST API

After conducting a test on a REST API using Postman, the outcome was as follows: { "success": true, "message": "success", "data": [ { "id_buku": 9, "judul_bu ...

Using jQuery to add a class to an input option if its value exists in an array

Looking for a way to dynamically add a class to select option values by comparing them with an array received from an ajax call. HTML <select id="my_id"> <option value="1">1</option> <option value="2">2</option> ...

Looking to convert a jQuery function to plain JavaScript code?

Struggling with my homework, I must apologize for any mistakes in my English. My task involves creating a chat using node.js and I found some code snippets on a website "" which I used successfully. The issue now is that the chat relies on old jQuery libr ...

"Utilizing Bootstrap to create a visually appealing image and text combination in the

I need to arrange the image, first span, and second span in a vertical stack for xs devices. The alignment should be centered for xs devices. If you want to see my code: CLICK HERE <div class="row"> <div> <div class="col-md-9 c ...

Steps for rearranging the order of CSS grid layout

Could you assist me in implementing a grid layout that fulfills these specific criteria? I'm unsure of how to proceed, so any guidance would be greatly appreciated. When there are more than 9 items, the current layout changes the order from top to bo ...

Ways to center items in a row-oriented collection

When dealing with a horizontal list, the issue arises when the first element is larger than the others. This can lead to a layout that looks like this. Is there a way to vertically align the other elements without changing their size? I am aware of manual ...

Expanding URL path parameters in Angular's ui-routerWould you like to

Can UI-router handle this type of routing? Parent state - /saved/:id Child state - /saved/:id/eat Here is the code snippet I am using. However, when I attempt to access it, the page redirects: .state('fruits.banana.saved', { url: &apo ...

Unable to upload any further verification documents to Stripe Connect bank account in order to activate payouts

Query - Which specific parameters should I use to generate the correct token for updating my Stripe bank account in order to activate payouts? I've attempted to activate payouts for my Stripe bank account by using a test routing and account number (t ...

Select multiple items from a list in HTML using the power of jQuery with a Multi Select

I'm facing an issue with the multi-select box. I attempted to choose multiple values using jQuery, but only the last one seems to be selected. Can someone assist me, please? Below is my code: <script> $(function(){ <?php foreach ($selectd ...

What are the proper methods for accurately testing vuex state and mutations?

Can someone guide me on how to properly test mutations and state? I have a modal window component that is rendered when the showModal property in the state is true. There is an event triggering a mutation that changes this property. How can I verify that a ...

Show a variety of pictures using React

Is it possible to repeat an image (e.g. photo.jpg) n times in Reactjs using a provided value for n in props? If yes, how can this be achieved? function Card(props) { for (let i = 0; i < props.rating; i++) { <img className="star" src ...