Eliminate repeated elements within the DOM

Are you looking to eliminate duplicate elements with the same classname (valid) from the DOM? Check out the example below:

<div class="content">
<div class="test1">
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
</div>  
<div class="test2">
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
</div>
</div>

The expected outcome should be:

<div class="content">
<div class="test1">
    <label class="valid">&nbsp;</label>
</div>  
<div class="test2">
    <label class="valid">&nbsp;</label>
</div>
</div>

Answer №1

To select and remove all elements except the first one, you can utilize the :nth-child pseudo-class selector.

$('.valid:nth-child(n+2)').remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
<div class="test1">
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
</div>  
<div class="test2">
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
</div>
</div>


You can also achieve this by combining the :first-child and :not() pseudo-class selectors.

$('.valid:not(:first-child)').remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
<div class="test1">
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
</div>  
<div class="test2">
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
</div>
</div>


Note: To initially hide the elements, you can apply the following CSS.

.valid:nth-child(n+2){
   display : none;
}

If you prefer not to use the jQuery library, you can achieve the same result using pure JavaScript.

// get all duplicate element and convert NodeList into an array
// use [].slice.call in older browsers to convert it to an array
Array.from(document.querySelectorAll('.valid:nth-child(n+2)'))
  // iterate over elements 
  .forEach(function(element) {
    // remove element from its parent
    element.parentNode.removeChild(element);
  });
<div class="content">
  <div class="test1">
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
  </div>
  <div class="test2">
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
    <label class="valid">&nbsp;</label>
  </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

Tips for displaying a div briefly before loading the second page

Incorporating a div named ADD, I aim to successfully load a second page within the current one using ajaxload. The challenge lies in displaying a div for 4 seconds before loading the second page. How can this be achieved? Following the wait period, the sec ...

Create animations for ng-repeat elements without using ng-animate

Can the transition for changing the order of the model array in ng-repeat be animated using only CSS, without using ng-animate? ...

Guidelines for validating email input using jQuery

Although I am not utilizing the form tag, you can still achieve form functionality using jQuery Ajax. <input type="email" placeholder="Email" name="email" /> <input type="password" placeholder="Password ...

Allow editing for only a specific part of a text box

Creating a customized personal URL page for users on my site is important to me. I envision the value of a text box being "example.com/username," with the "example.com/" part displayed in the text box, but not editable. I've noticed that Tumblr accom ...

How to activate an ASP.NET LinkButton using JavaScript

I've set up a page to hide a FileUpload control, so that when a button is clicked, it displays the file upload window and automatically submits the selected file to the server. To make this work, I created two linkbuttons and a file upload control, b ...

Scrollbar not appearing when overflow-y is set in React Textarea Input on Chrome or Edge

I've been struggling to add a scrollbar to a React Textarea. I've referred to an old post on Stack Overflow here and a few other resources, but haven't had any luck. I've tested it in both Chrome (Version 113.0.5672.129) and Edge (Vers ...

Ways to show a div element within an input field?

I want to incorporate tags similar to stackoverflow on my website. Users will be able to create tags for filtering results, searching, showcasing expertise, and more. I have managed to create tags, but I am struggling to display them inside an input box l ...

Steps for linking two MySQL tables

I have a table named "products" in my MySqli Database. Products TABLE product_id | INT primary KEY product_name | VARCHAR(50) product_price | float When entering rows into the products table from PHP, I use the following code: mysq ...

Transform your standard HTML buttons into a collective of radio buttons

Looking for a way to make some ordinary buttons function as radio buttons without adding another library to the project. Any suggestions on how this can be achieved using just HTML and JavaScript/jQuery? Appreciate any help, thank you. ...

Jquery Mobile: Navigating back to the first page after calling changePage

In the process of developing a mobile app with phonegap/cordova and jquery mobile, I encountered an issue where the user is supposed to land on a specific page from a status bar notification. However, the app initially displays the default page briefly bef ...

Using Django to render multiple images for a post

For the past few days, I have been attempting to provide the admin user with the ability to upload multiple images/slides for each individual post. One idea that came to mind was nesting a for loop inside the posts' for loop so that for every post, al ...

Adjust the transparency level when hovering in an R Shiny application

I have an absolute Panel in my R shiny app and I am attempting to adjust its opacity based on the mouseover action. The goal is to have the opacity at 1 when the cursor is on the panel, and 0.5 otherwise. However, the code I tried ended up making the pane ...

Creating dynamic select boxes in Django Admin using jQuery

In my Contract class, the contract_mod field is designed to extend a contract from a previous one and should only display contracts related to the selected person. The Contract class returns the person field, but since I have no experience with AJAX/jQuery ...

The data-tooltip feature displays information as [Object object]

There seems to be an issue with displaying text in the data-tooltip. Instead of showing the intended message, it is displaying [Object object]. import React from "react"; import { FormattedMessage } from "react-intl"; const translate = (id, value={}) = ...

Navigation bar with a full-page slider

I am trying to incorporate my bootstrap nav bar into a full-width slider, similar to the layout in this example. https://i.sstatic.net/LE9wP.jpg This is the full width slider http://codepen.io/grovesdm/pen/MazqzQ Currently, I have positioned the nav ba ...

There is currently no graph being shown

I've run this code but I'm not getting any output. There are no errors showing up, but I can't seem to figure out what's wrong. Can someone help me identify the issue? Thanks! <!DOCTYPE html> <html> <head> <m ...

Rearrange the text next to the Checkbox using Bootstrap

I'm having trouble aligning the "Default checkbox" text next to the checkbox itself checkbox This is what I've attempted so far <div class="col-2"> <label for="Desc" class="col-sm col-form-label">D ...

Google Visualization issue; "Invalid data type"

I'm attempting to make a simple $.ajax GET request to fetch data from an API and connect it to Google Charts. The data returned by my API looks like this: https://i.sstatic.net/3tn1Z.png This is the format that the Google documentation specifies for ...

Is there a reason to not simply reset the connection to the $.ajax?

Ensure that the server is available before loading the scripts. On the client side jQuery(document).ready(function(){ jQuery.ajax({ dataType: "jsonp", timeout: 1000, cache: false, url: "http://xxx/include/xxx.php?q=? ...

Using data-attribute, JavaScript and jQuery can be used to compare two lists that are ordered

I am looking to implement a feature that allows me to compare two lists using data attributes in either JavaScript or jQuery. Unfortunately, I haven't been able to find any examples of this online and I'm not sure how to approach it. The first l ...