Jquery: Remove the Second Instance of Element... in particular element

So I have…

<div class="data">
<div class="variation-gallery"></div>
<div class="variation-gallery"></div> <!-- remove this -->
</div>
<div class="other-div"></div>
<div class="data">
<div class="variation-gallery"></div>
<div class="variation-gallery"></div> <!-- remove this -->
</div>

I want to remove the second instance of an element, if it appears in a particular element. So remove the second div with class “variation-gallery” when inside the element with class “data”

Remove the second one for each element “data”, or the last one, since there is always only two “variation-gallery” elements for every “data” element.

What is the right jquery code to do so?

All feedback appreciated.

Cheers!
Ryan

if we assume that the two classes don’t randomly appear anywhere else in your page we could do something like this:

// this selector should be able to target  the elements  you want 

let items = $('.data  > .variation-gallery:nth-of-type(2)'); 

//this vanilla js  iterates though the collection and  removes  the elements one by one.
// also if you you need to keep the elements for later use you could  create a variable and use the .map() method instead of .forEach

Array.prototype.forEach.call( items,  item =>  item.parentNode.removeChild( item ));

hope that helps

1 Like

items.remove()

alternatively:
$('.data').remove(".variation-gallery:nth-of-type(2)");

(We’re already committed to using jQuery, might as well use the power of the framework!)

3 Likes

I know this was a js question but CSS could hide it also. :slight_smile:

.data .variation-gallery ~ .variation-gallery{display:none;}

2 Likes

Thanks so much everyone! @PaulOB - I actually said hide() for testing, I need to REMOVE function these once I ensure the hide is working. :slight_smile: That’s why I needed a js/jquery solution. In Wordpress I have two plugins conflicting, creating the second element, which is creating a redundancy issue every time I update a page, so this will remove the redundancy as it is created.

Cheers!
Ryan

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.