0

I've written a code in jQuery as follows

$(document).ready(function() {
  $("li").click(function() {
    var str = $(this).index();
    alert(str);
    $("#headdiv div:nth-child(" + str + ")").addClass("product-active");

  });
});

I want to pass the value stored in the str variable as a nth child index number. Where i'm doing wrong?

0

3 Answers 3

1

Increment the str variable with 1 everytime you click. See the working snippet below:

$(document).ready(function() {
  $("li").click(function() {
    var str = $(this).index();
    str++;
    //console.log(str);
    $("#headdiv div:nth-child(" + str + ")").addClass("product-active");

  });
});
.product-active{
  color: #F00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>List element</li>
  <li>List element</li>
  <li>List element</li>
  <li>List element</li>
  <li>List element</li>
</ul>
<div id="headdiv">
  <div>some div</div>
  <div>some div</div>
  <div>some div</div>
  <div>some div</div>
  <div>some div</div>
</div>

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

1 Comment

@shyamm, awesome. I'm happy to help.
0

You should add str++.

Because the str keyword is creating a new variable every time in your every load so global variable str is not getting updated/incremented.

$(document).ready(function() {
  $("li").click(function() {
    var str = $(this).index();
    str++;
    $("#headdiv div:nth-child(" + str + ")").addClass("product-active");

  });
});
.product-active {	
	background-color: green !important;
}
.not-active{
  background-color: red;
  height: 50px;
  margin-right: 5px;
  width: 50px;
  border-radius: 50%;
  float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>Click Me</li>
  <li>Click Me</li>
  <li>Click Me</li>
</ul>
<div id="headdiv">
  <div class="not-active"></div>
  <div class="not-active"></div>
  <div class="not-active"></div>
</div>

Comments

0

We are creating a variable and appending the text with the str value and then using that string in the jQuery.

$(document).ready(function() {
      $("li").click(function() {
        var str = $(this).index();
        alert(str);
        //Create a new variable
       var buildStr = "#headdiv div:nth-child(" + str + ")";
        $(buildStr).addClass("product-active");

      });
    });

2 Comments

answering with code without explanation is not a good practice
use var when declaring a variable in javascript buildStr

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.