Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

javascript - jQuery :contains(), but to match an exact string

As said in the title, I'd like to find something like :contains() but to match an exact string. In other words, it shouldn't be a partial match. For example in this case:

<div id="id">
   <p>John</p>
   <p>Johny</p>
</div>

$("#id:contains('John')") will match both John and Johny, while I'd like to match only John.

Thanks in advance.

EDIT: ES2015 one-liner solution, in case anyone looked for it:

const nodes = [...document.querySelectorAll('#id > *')].filter(node => node.textContent === 'John');

console.log(nodes);
/* Output console formatting */
.as-console-wrapper { top: 0; }
.as-console { height: 100%; }
<div id="id">
  <p>John</p>
  <p>Johny</p>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use filter for this:

$('#id').find('*').filter(function() {
    return $(this).text() === 'John';
});

Edit: Just as a performance note, if you happen to know more about the nature of what you're searching (e.g., that the nodes are immediate children of #id), it would be more efficient to use something like .children() instead of .find('*').


Here's a jsfiddle of it, if you want to see it in action: http://jsfiddle.net/Akuyq/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...