80757

jQuery - Grouping multiple elements with the same class

Question:

I have a bunch of elements that all belong to a section of a certain number.

<div class="section-1"></div> <div class="section-1"></div> <div class="section-2"></div> <div class="section-2"></div> <div class="section-2"></div> <div class="section-3"></div> <div class="section-4"></div> <div class="section-4"></div> ...

I want to wrap each group of the same section elements with a parent element, even sections that occur only once.

This is a quick and working, but very dirty solution that I came up with:

$('.section-1').wrapAll('<div class="parent-section">'); $('.section-2').wrapAll('<div class="parent-section">'); $('.section-3').wrapAll('<div class="parent-section">'); $('.section-4').wrapAll('<div class="parent-section">'); $('.section-5').wrapAll('<div class="parent-section">'); $('.section-6').wrapAll('<div class="parent-section">');

I tried to come up with a slightly more elegant solution by using each()

$('.section-1,' + '.section-2,' + '.section-3,' + '.section-4,' + '.section-5,' + '.section-6').each(function () { $(this).wrapAll('<div class="parent-section">'); });

But then I realised that this will wrap each individual occurrence of every class name and not wrap them as a group.

On top of that, while currently there are only 6 sections, there might be more in the future (7, 8, 9, 10, 11 etc.), so it would be great if the function could work with any number of sections.

Any help is much appreciated.

Answer1:

<a href="https://jsfiddle.net/yje5frds/1/" rel="nofollow">You may try this</a>:

// Get all the classes var classes = $('[class^=section]').map(function() { return $(this).attr('class'); }); // Filter only unique ones var uniqueClasses = $.unique(classes); // Now group them $(uniqueClasses).each(function(i, v) { $('.'+v).wrapAll('<div class ="parent-'+v+'"></div>'); });

In this example, each group will be inside a parent div with class name parent-section-1, parent-section-2 and so.

Recommend

  • Wrap groups of elements using jQuery
  • Selecting element having two classes and wrapping them
  • jquery slide back and forth or slide round
  • console.log printing statements in the wrong order for learnyounode node.js tutorial
  • DML and Exception Handling - Oracle
  • jquery add an event handler to objects in an array
  • Where in the relevant specification is it documented that some comments in a SQL script are, in fact
  • iOS custom UTI in UIDocumentPickerViewController initWithDocumentTypes
  • GitHub default README markup
  • Is there any purpose for h2-h6 headings in HTML5?
  • Set focus to first invalid form element in AngularJS
  • How to autopopulate a field in SugarCRM form
  • Clear activity stack before launching another activity
  • Force show.bind execution
  • C: Incompatible pointer type initializing
  • why xml file does not aligned properly after append the string in beginning and end of the file usin
  • Disable Enter in editText android
  • Python CGI os.system causing malformed header
  • Read text file and split every line in MSBuild
  • Why ng-show works with ng-repeat but ng-if doesn't? [duplicate]
  • C# - Serializing and deserializing static member
  • Excel - Autoshape get it's name from cell (value)
  • How to add a column to a Pandas dataframe made of arrays of the n-preceding values of another column
  • Check if a string to interpolate provides expected placeholders
  • Perl system calls when running as another user using sudo
  • Arrow is showed instead of the material design version hamburger icon. Why doesn't syncState in
  • Why is the timeout on a windows udp receive socket always 500ms longer than set by SO_RCVTIMEO?
  • Weird JavaScript statement, what does it mean?
  • R: gsub and capture
  • RestKit - RKRequestDelegate does not exist
  • Traverse Array and Display in markup
  • Matrix multiplication with MKL
  • Unit Testing MVC Web Application in Visual Studio and Problem with QTAgent
  • Hits per day in Google Big Query
  • embed rChart in Markdown
  • File not found error Google Drive API
  • Linking SubReports Without LinkChild/LinkMaster
  • Easiest way to encapsulate a HTML5 webpage into an android app?
  • Django query for large number of relationships
  • Converting MP3 duration time