2

I've looked through some documentation, but I feel like there's an easier method to remove one item from an array without using an iteration loop.

http://jsfiddle.net/G97bt/1/

Updated jsFiddle: http://jsfiddle.net/G97bt/6/ using not()


<button id="1">1</button>
<button id="2">2</button>
<button id="3">3</button>

<div id="1a">Test</div>
<div id="2a">Test</div>
<div id="3a">Test</div>

var $myList = $("#1a, #2a, #3a");

$("#1").on("click", function() {
    $myList.fadeOut(); // I want to fade DIVs #2a + #3a, not ALL
    $("#1a").fadeIn("slow");    
});
$("#2").on("click", function() {
    $myList.fadeOut(); // I want to fade DIVs #1a + #3a, not ALL
    $("#2a").fadeIn("slow");    
});
$("#3").on("click", function() {
    $myList.fadeOut(); // I want to fade DIVs #1a + #2a, not ALL    
    $("#3a").fadeIn("slow");    
});

This is how I'm envisioning it would function:

$myList.remove['#1a'].fadeOut();
3
  • 2
    javscript .splice() ? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Mar 31, 2014 at 13:40
  • .filter is your buddy Commented Mar 31, 2014 at 13:41
  • Ugh. I even read through using splice() but it didn't click. Thank you, and sorry for a silly question :) Commented Mar 31, 2014 at 13:42

3 Answers 3

10

Like below, by using .not to remove elements from the set of matched elements:

$myList.not('#1a').fadeOut();

And note $myList is not an array but a jQuery object(even it behaves like an array).

You could also rewrite your code like below:

var $myList = $("#1a, #2a, #3a");

$("#1,#2,#3").on("click", function() {
    $myList.not('#'+this.id+'a').fadeOut();
    $('#'+this.id+'a').fadeIn("slow");    
});

The working demo.

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

2 Comments

@Sophisticake Because .not() is designed to do such job. And splice() is a method of array, not jQuery object. splice() returns the removed element by position, etc...
0

You can use like this

$("button").click(function(){
  $("[id$=a]").hide();

  $("#"+this.id+"a").show();
});

Comments

0

Use

$arrayName.splice(position, number of elements)

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.