Reputation: 28437
You can put a variable inside nth-child like so:
var myVar = $(elem);
$("div:nth-child(" + myVar + ")");
But how can you put the value of nth-child inside a var? I don't think that nth-child is the appropriate term, but I don't know what else to call it. I mean: get which child the element is and put it in a var.
For instance, take a look at this fiddle: HTML
<div>
<p>Text 1</p>
<p>Text 2</p>
<p>Text 3</p>
</div>
<button>1</button>
<button>2</button>
<button>3</button>
jQuery
$("button").click(function() {
var $this = $(this),
thisNumber = // which child is it? as a numeric value;
$("p:nth-child(" + thisNumber + ")").toggle("fast");
});
Upvotes: 0
Views: 96
Reputation: 104775
I think you want something like this:
$("button").click(function() {
$("p:nth-child(" + $(this).index() + ")").toggle();
});
Demo: http://jsfiddle.net/KFXnN/3/
Upvotes: 3
Reputation: 14575
You are overcomplicating this :) , you don't need any variables, just $(this).index()
$("button").click(function() {
$("p:nth-child(" + $(this).index() + ")").toggle("fast");
});
Upvotes: 4
Reputation: 324620
Sometimes, the solution is a lot simpler than you think ;)
Upvotes: 4