0

Example:

<div id="Elmnt_1" class="MyElement">
<div id="Elmnt_2" class="MyElement">
<div id="Elmnt_3" class="MyElement">
<div id="Elmnt_4" class="MyElement">

How to select all element which have class="MyElement" and omit one element from it using specific id

My guess:

var fltrdElmnts = $(".MyElement").filter(! $( "#Elmnt_2" ) );
fltrdElmnts.remove();

Expected result:

<div id="Elmnt_2" class="MyElement">
3
  • How about just using $('#Elmnt_3') when you just want to get that element only? Commented Mar 5, 2018 at 15:16
  • @palash actually i want to hide all elements exept one specific element Commented Mar 5, 2018 at 15:26
  • Ok, I was bit confused as you had the code fltrdElmnts.remove(); which is unnecessary, if you just want one element. Commented Mar 5, 2018 at 15:27

3 Answers 3

2

You can use :not() pseudo class inside selector.

$(".MyElement:not(#Elmnt_2)")

$(".MyElement:not(#Elmnt_2)").css('color', 'red')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Elmnt_1" class="MyElement">Div</div>
<div id="Elmnt_2" class="MyElement">Div</div>
<div id="Elmnt_3" class="MyElement">Div</div>
<div id="Elmnt_4" class="MyElement">Div</div>

Or you can use .not() method.

$(".MyElement").not('#Elmnt_2')

$(".MyElement").not('#Elmnt_2').css('color', 'red')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Elmnt_1" class="MyElement">Div</div>
<div id="Elmnt_2" class="MyElement">Div</div>
<div id="Elmnt_3" class="MyElement">Div</div>
<div id="Elmnt_4" class="MyElement">Div</div>

Sign up to request clarification or add additional context in comments.

Comments

2

You could use the :not() selector for that

var fltrdElmnts = $(".MyElement:not(#Elmnt_2");

Demo:

$(function() {
  var fltrdElmnts = $(".MyElement:not(#Elmnt_2");
  fltrdElmnts.remove();
  /* or just:
  $(".MyElement:not(#Elmnt_2").remove();
  */
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Elmnt_1" class="MyElement">Elmnt_1</div>
<div id="Elmnt_2" class="MyElement">Elmnt_2</div>
<div id="Elmnt_3" class="MyElement">Elmnt_3</div>
<div id="Elmnt_4" class="MyElement">Elmnt_4</div>

Comments

1

Use this selector MyElement:not(#Elmnt_2)

var fltrdElmnts = $(".MyElement:not(#Elmnt_2)");
fltrdElmnts.remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Elmnt_1" class="MyElement">a</div>
<div id="Elmnt_2" class="MyElement">b</div>
<div id="Elmnt_3" class="MyElement">c</div>
<div id="Elmnt_4" class="MyElement">d</div>

Doc

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.