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

What is the reason why setting 'onClick' as an event handler is not flagged as a syntax error?

I am currently working on a JavaScript code snippet where I am trying to change the headline text when it is clicked. The code I have written is: var headline = document.getElementById("mainHeading"); headline.onClick = function() { headline.innerHTML ...

Creating key elements in JavaScript with the push() function

I'm working on a basic shopping cart system using JavaScript (Ionic 2 / Angular). In my PHP code, I have the following: <?php $cart = array( 48131 => array( 'size' => 'STANDARD', 'qty' => ...

Two Elements Linked Together

I'm facing an issue with my interconnected React components. Despite being separate entities, they appear to share some styling attributes which I find puzzling. The main problem lies in the footer component as it seems linked to another component, p ...

Ways to incorporate debounce time into an input search field in typescript

Is there a way to incorporate debounce time into a dynamic search box that filters data in a table? I have explored some solutions online, but my code varies slightly as I do not use throttle or similar functions. This is my template code: <input matI ...

React - The `component` prop you have supplied to ButtonBase is not valid. Please ensure that the children prop is properly displayed within this customized component

I am attempting to use custom SVG icons in place of the default icons from Material UI's Pagination component (V4). However, I keep encountering this console error: Material-UI: The component prop provided to ButtonBase is invalid. Please ensure tha ...

Issues occurring with setting the variable using the Google latlng API

I've tried searching for solutions on various forums, including stackoverflow, but haven't been able to make it work. The issue lies in this code snippet where the variable 'pos' is not being set: var geocoder= new google.maps.Geocoder ...

The validation feature in ASP.NET MVC does not seem to be functioning properly while using

I'm struggling to make the bootstrap modal and asp.net mvc validation work together seamlessly. My form is quite complex with validation displayed in a bootstrap modal. However, when I press the submit button, the validation doesn't seem to be fu ...

Looking for a Horizontal Layout?

@foreach (var item in APModel) { <div class="row row-cols-1 row-cols-md-2 g-4"> <div class="col"> <div class="card" style="width: 18rem;"> <img src="h ...

Adjustable Panel Width

Is there a way to have the width of the bottom panel expand to col-md-12 when the top panel is collapsed, and then return back to col-md-8 when the user expands the top panel again? I'm still learning, but here's what I have managed to code so f ...

Learn the best way to utilize a stylus in Vue files to interact with JavaScript variables

For instance: <script> export default { data() { return{ varinjs: 1, } } } </script> <style lang="stylus"> varincss = varinjs body if varincss == 0 ba ...

Ways to employ data binding for extracting a user-input value and performing multiplication operations with the enclosed {{ ...}} tags

My API response includes the price of a product, which is represented as {{price}} I have a system where I can add or reduce the number of products: <div class="number-input"> <h2>Price: {{price }}</h2> <button oncli ...

What is the best way to use CSS to hyphenate a capitalized word?

I have a single word that needs to be hyphenated, but the lang=en hyphenate: auto property does not work on capitalized words. To address this, I utilized the slice function in JavaScript to split the word in half so that the second half, which requires h ...

Error in Node.js (NPM Error)

Recently, I purchased a VPS running Ubuntu 14.4 and successfully installed Node.js 1.4. However, when attempting to run my script (node tradebot.js), I encountered the following error message! :-/ module.js:327 throw err; ^ Error: Cannot find ...

The page you are looking for cannot be located using Jquery AJAX JSON PHP POST -

Whenever I attempt to POST some JSON data to a local host, I consistently encounter a 404 Not Found error. Strangely enough, the php file is positioned precisely where it should be according to the script instructions. If anyone has dealt with this issue b ...

How can I delete the black background from the ion-tab-bar in Ionic 7?

In my current project using Ionic 7, I have a navigation guide set up with 4 tabs. I am trying to customize the styling of these ion tabs by adding some custom CSS. The issue I'm facing is that despite my attempts to make the background transparent, ...

How can CSS be used to center multi-line text with the shortest line appearing at the top

I'm currently working on some html and css code that looks like this: <div style="width: 40em; text-align: center;"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard du ...

What is the best way to eliminate items from an array in a side-scrolling video game?

In my gaming project, I am creating a unique experience where the player needs to collect all the words from a given array. Currently, I am utilizing the shift() method to eliminate elements, as demonstrated in the code snippet below: if ( bX + bird.width ...

Ways to access elements and their associated values in a JavaScript Array

I'm facing a challenge with a JavaScript array where I need to extract teams (Team A, Team B) and organize them into one array while preserving their order. See below for the current output of the array, as well as the JS code provided and the expecte ...

Develop a video in mp4 format using Node.js and ffmpeg by combining two or more jpg images

I am currently working on a video animator project where I generate .jpg images from an html canvas tag and then use these images as frames for the video. The tool I am using for video generation is ffmpeg. Successful with Single Image const ffmpeg = req ...

Tally the number of words entered in the text box

Is there a way to make the keyword search in a text area live, rather than requiring the user to manually initiate the search? I have a working code that counts the number of times a specific keyword is used within the text, but it currently requires the u ...