memaxt
memaxt

Reputation: 57

Remove Duplicate div class with JQuery

For some odd reason my website is duplicating a div element. Before I try to find the reason why it's being duplicated, I'm looking into a way of temporarily hiding the duplicated div.

I've tried the following script:

 $(document).ready(function() {
     $('.ms-account-wrapper').eq(1).remove();
 });

html:

<div class="ms-account-wrapper">1</div>
<div class="ms-account-wrapper">2</div> <---want to remove this one

Any ideas?

Many thanks

Max

Upvotes: 3

Views: 9666

Answers (6)

Mustapha Larhrouch
Mustapha Larhrouch

Reputation: 3393

try this:

<script>
 $(document).ready(function() {
      $('.ms-account-wrapper:last').remove();
 });
 </script>

Upvotes: 2

Mayank Sharma
Mayank Sharma

Reputation: 83

try this:-

<script>
   $(document).ready(function() {
       $('.ms-account-wrapper').first().nextAll().remove();
   });
</script>

Upvotes: 1

Haresh Vidja
Haresh Vidja

Reputation: 8496

You can achieve this

$(document).ready(function() {
 $('.ms-account-wrapper').not(':first').remove();
});

Working Example (here will remove after 3 seconds for demo purpose)

 setTimeout(function(){$('.ms-account-wrapper').not(':first').remove();},3000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ms-account-wrapper">1</div>
<div class="ms-account-wrapper">2</div>
<div class="ms-account-wrapper">3</div>
<div class="ms-account-wrapper">4</div>
<div class="ms-account-wrapper">5</div>

Upvotes: 0

$(document).ready(function() {
   var _divs = $('.ms-account-wrapper');
   // Ensure there is more than 1
   if (_divs.length > 1){
      for(var i=1;i<_divs.length;i++)
          _divs[i].remove();
   }
});

you can try this...it works if more than 2 also

Upvotes: -2

Brett Gregson
Brett Gregson

Reputation: 5913

Select and remove() all elements with the .ms-account-wrapper class except the first:

$(".ms-account-wrapper:not(:first)").remove();

This works regardless of how many .ms-account-wrapper elements there are

Working example

Upvotes: 8

Sinan Guclu
Sinan Guclu

Reputation: 1087

The jQuery selector will return an array of all the elements with that class. You can refer to the second element like you would an index of an array:

$(document).ready(function() {
  var _divs = $('.ms-account-wrapper');
  // Ensure there is more than 1
  if (_divs.length > 1)
    _divs[1].remove();
});

Here is a codepen.

Upvotes: 1

Related Questions