mon-sun
mon-sun

Reputation: 105

jquery selector with same class

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.

Upvotes: 1

Views: 71

Answers (3)

RyanM
RyanM

Reputation: 761

Do this:

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

Upvotes: 0

MervS
MervS

Reputation: 5902

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)

Upvotes: 3

guradio
guradio

Reputation: 15555

$('.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

Upvotes: 2

Related Questions