1

I am having a click handler for three buttons and inside this handler I want to extract ID of the button clicked. I have a line of code like this:

$('#switch button').click(function(){
    var class=this.id.split('-')[1];
    // rest of the code 
});

I do understand the split method, but can't understand [1] index in the end?

Assume that I have a id named say switch-default.

3
  • 1
    Your code does not extract class name, but rather the id of the clicked element. To get class name, change the code to this: var class = this.className; Feb 12, 2012 at 13:50
  • @ShadowWizard correct. I have edited my question.
    – HalfWebDev
    Feb 12, 2012 at 13:59
  • Cheers, as the answers all say the code will give the second part after splitting by - for example for such button: <button id="my-first-button">first</button> it will be "first". Feb 12, 2012 at 14:01

3 Answers 3

4

It is the index of the element in the newly created array, so [1] refers to the second element. To make it clear:

var classes = this.id.split('-');
console.log(classes[0] + " " + classes[1]); // outputs "switch default"

See:

4

string.split() returns an array. Example:

var foo = "example-123";
var bar = foo.split("-");     // => ["example", "123"]
var baz = foo.split("-")[1];  // => "123", the same as bar[1]
0

The split function returns an array. As such you can select elements of the array using the [1]. Arrays element indexes start at 0, so the first element is 0 and the second is 1 and so on.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.