Reputation: 467
I have the following code in my HTML:
<li class="strange">1</li>
<li class="strange">2</li>
<li class="strange">3</li>
<li class="strange">4</li>
I want to choose the exact <li>
which contains number '3'
as a Text.
Is there any method to choose the exact element?
Can we choose by using some OO-JS methods?
Upvotes: 2
Views: 713
Reputation: 6031
try using jQuery selector :contains
Description: Select all elements that contain the specified text.
$('li:contains("3")')
Match exact text
As per @Raoulito mention in his comment here updated answer which match exact text using jQuery filter().
Description: Reduce the set of matched elements to those that match the selector or pass the function's test.
$(document).ready(function(){
$("li").filter(function() {
return $(this).text() === "3";
}).css("color", "red");
});
Upvotes: 2
Reputation: 361
This only select the element which has exactly '3' as text:
$('li.strange').each(function() {
if ( $(this).text() == '3' ) {
$(this).css('color','red');
}
});
http://jsfiddle.net/dremztou/1/
$('li.strange:contains("3")').addClass('selected');
would select all the elements containing 3, including 13, 23, 33, etc.
Upvotes: 0
Reputation: 1377
If you want to use just javascript you can do something like that:
HTML
<ul id="ul">
<li class="strange">1</li>
<li class="strange">2</li>
<li class="strange">3</li>
<li class="strange">4</li>
</ul>
Javascript
var nums = document.getElementById("ul"); // get the ul element
var listItem = nums.getElementsByClassName("strange"); //fetch all elements inside the ul that have a class of strange
var element;
// loop through the list elements
for (var i=0; i < listItem.length; i++) {
// check whether list's inner html is equal to 3
if (parseInt( listItem[i].innerHTML) == 3) {
// set the value of element equal to the list element
element = listItem[i];
break;
}
}
console.log(element); // logs out the element that has the required value, you can use element.innerHTML to check
Upvotes: 0