2

How can I check for a specific character in a element?

<div>N0180/RIB</div>
<div>N0180918</div>
<div>N0180</div>

**(I want to target <div>N0180</div> this element)**

I tried to use :contains("N0180") and .substring method. But it is target all three elements.

3 Answers 3

3

As per :contains() Doc:

The matching text can appear directly within the selected element, in any of that element's descendants, or a combination thereof. As with attribute value selectors, text inside the parentheses of :contains() can be written as a bare word or surrounded by quotation marks. The text must have matching case to be selected.

You can rather use .filter() for more specific comparison :

$('div').filter(function(){
   return $(this).text().trim() === "N0180";
})
Sign up to request clarification or add additional context in comments.

1 Comment

But function can be independent...method can not be..And that is the reason they have used the term method in the docs.. the .filter() method constructs a new jQuery object from a subset of the matching elements.
0

For exact match use .filter()

$('div').filter(function(){
    return $(this).text().trim() == "N0180";
})

Note: For case-insensitive search convert the values to same cases using toLowerCase() or .toUpperCase()

Comments

0

$('div').each(function() {

  if ($(this).text() === 'N0180') {

    $(this).addClass('red')

  }


})
.red {
  color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>N0180/RIB</div>
<div>N0180918</div>
<div>N0180</div>

You can get the .text() of div and compare to your text

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.