Davod naroea
Davod naroea

Reputation: 21

Get nth-child in jquery javascript

i want to get nth-child an object for example

<div>
<img src="1.jpg" />
<img src="2.jpg" />
<img src="3.jpg" />
</div>

in jquery.

function func(i){
$("div img:nth-child(i)).css("display","none");
}

but i in double quotation Does not work. I want to know another way.

Upvotes: 1

Views: 47

Answers (3)

hawkstrider
hawkstrider

Reputation: 4341

Just concatenate the variable in

function func(i){
    $("div img:nth-child(" + i + ")").css("display","none");
}

Or using template litterals https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

function func(i){
    $(`div img:nth-child(${i})`).css("display","none");
}

Upvotes: 2

Rohit.007
Rohit.007

Reputation: 3502

To achieve the dynamic nth-child you can generate the selector with dynamically added value.

Check the working code:

function func(i) {
  $("div img:nth-child(" + i + ")").css("display", "none");
}

func(2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <img src="1.jpg" />
  <img src="2.jpg" />
  <img src="3.jpg" />
</div>

Upvotes: 1

iiirxs
iiirxs

Reputation: 4582

The problem is not the double quotations, your syntax is wrong. Try: $("div img:nth-child(" + i + ")").css("display","none");

Upvotes: 0

Related Questions