Reputation: 105
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
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
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