Sundar
Sundar

Reputation: 467

Selecting a particular DOM element using JavaScript

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

Answers (5)

Nishit Maheta
Nishit Maheta

Reputation: 6031

try using jQuery selector :contains

Description: Select all elements that contain the specified text.

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

DEMO

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");
}); 

DEMO

Upvotes: 2

Raoulito
Raoulito

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

kidA
kidA

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

ketan
ketan

Reputation: 19341

Using JavaScript you can do like:

 var list = document.getElementsByClassName("strange");

 for (i = 0; i < list.length; i++) {
if(list[i].innerHTML ==3)
  {
    list[i].style.color = "blue";
     list[i].style.backgroundColor = "red";
   }
 }

Check Fiddle.

Upvotes: 0

Sadikhasan
Sadikhasan

Reputation: 18600

Try with jQuery contains

$('li:contains("3")');

Demo

Upvotes: 0

Related Questions