Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery text match

Tags:

jquery

I have an anchor tag with text and I want to check if the given var matches the string exactly.

This works, but I would like to use something other than contains, since it will match two elements if the contain the given string. I want it to match exactly.

Any ideas ?

function test(submenu){
$('a:contains("' + submenu + '")', 'ul.subMenu li').css('font-weight', 'bold');
}
like image 248
Gabe Avatar asked Dec 10 '09 20:12

Gabe


People also ask

How do I find a word in a string using jQuery?

How to find if a word or a substring is present in the given string. In this case, we will use the includes() method which determines whether a string contains the specified word or a substring. If the word or substring is present in the given string, the includes() method returns true; otherwise, it returns false.

How do I search for text in a div?

To check if a div element contains specific text:Use the textContent property on the element to get the text content of the element and its descendants. Use the includes() method to check if the specific text is contained in the div . If it is, the includes() method returns true , otherwise false is returned.

How do I get text inside a div using jQuery?

To get the value of div content in jQuery, use the text() method. The text( ) method gets the combined text contents of all matched elements. This method works for both on XML and XHTML documents.

How can I get next sibling in jQuery?

jQuery next() Method The next() method returns the next sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward along the next sibling of DOM elements.


2 Answers

You can use the .filter() function instead of the :contains filter to apply a custom filter to your selector result set.

In this case apply a custom filter to look for text with an exact match. Something like:

$('a').filter( function (index) {
    return $(this).text() == submenu;
})
  .css('font-weight', 'bold');
like image 118
womp Avatar answered Sep 22 '22 13:09

womp


Is this what you're looking for:

function test(submenu)
{
   if ($("ul.submenu li a").text() == submenu)
   { 
      // do whatever here 
   }
}

However, I'm not sure what you mean by, "This works, but I would like to use something other than contains, since it will match two elements if the contain the given string. I want it to match exactly."

like image 38
ryanulit Avatar answered Sep 26 '22 13:09

ryanulit