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');
}
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.
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.
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.
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.
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');
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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With