1

How to select li in repeated ul with same class at click event

<div id="holder">

  <ul class="pattern">
     <li>1</li>
     <li>2</li>
     <li>3</li>
  </ul>
  <ul class="pattern">
     <li>4</li>
     <li>5</li>
     <li>6</li>
  </ul>
  <ul class="pattern">
     <li>7</li>
     <li>8</li>
     <li>9</li>
     <li>10</li>
  </ul>

</div>

i want to select/get the li with number 5(ex only), pls assume that i have a bunch of ul with same classes.

since i have a lot of ul, im looking for selecting the index of ul then select the li.

1
  • pls check my answer it will help Commented Oct 30, 2015 at 2:46

3 Answers 3

3

You can use jQuery's :contains selector:

 $("li:contains('5')")

For example:

$("ul.pattern").click(function(){
  var index = $(this).index();
  console.log(index);
  $("ul.pattern").eq(index).find("li:contains('5')").css("background","red");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="holder">

  <ul class="pattern">
     <li>1</li>
     <li>2</li>
     <li>3</li>
  </ul>
  <ul class="pattern">
     <li>4</li>
     <li>5</li>
     <li>6</li>
  </ul>
  <ul class="pattern">
     <li>7</li>
     <li>8</li>
     <li>9</li>
     <li>10</li>
  </ul>

</div>

Edit: Code updated to get current index of currently clicked ul using index() and locating the specific li among all ul's with the text 5 by using eq() and find() (with the :contains selector)

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

3 Comments

actually i dont have any content in my li, my scenario is, when li is click ( get the dom position and return something .html("blablabla") )
I suppose you may need to modify your question to include your requirement.
Not sure about your specific use-case but see the edit.
2

$('.pattern li').click(function() {
  console.log($(this).index())
  console.log($(this).text())
  console.log($('.pattern').find('li:eq(' + $(this).index() + ')').text())

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="holder">

  <ul class="pattern">
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
  <ul class="pattern">
    <li>4</li>
    <li>5</li>
    <li>6</li>
  </ul>
  <ul class="pattern">
    <li>7</li>
    <li>8</li>
    <li>9</li>
    <li>10</li>
  </ul>

</div>

Try this way

Comments

0

Do this:

$('<li>').val() == 5;

1 Comment

Please consider editing your post to add more explanation about what your code does and why it will solve the problem. An answer that mostly just contains code (even if it's working) usually wont help the OP to understand their problem.

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.