简体   繁体   中英

Check if a value already exists on a <li> tag with jQuery

I need to know with jQuery if a certain value is on a <li> tag on an <ul> with a certain tag:

<ul id="timeline">
<li>MyValue</li>
<li>MySecondValue</li>
</ul>

How can I check with jQuery if for example, MySecondvalue , is already on the the <ul> with the timeline id? Thanks!

$("ul li").filter(function() {
    return $(this).text() == "MySecondValue";
}).length;

If that expression returns 0, it is not on the list. Otherwise, it is.

if ( $('ul li:contains("MySecondValue")').length ) {
    //exists
}

do something like this:

$('ul li').each(function(){ 
     if($(this).text()=='MySecondvalue') alert('already exists');
}

Not quite jQuery-ish, but depending on the number of elements to filter, this could be the most performant way:

function alreadyInTimeline(text) {
    return ($('#timeline').html().match(new RegExp('\>(' + text + ')\<')) !== null);
}

alert(alreadyInTimeline('MyValue'));

cf. the performance comparison of the answers given here so far on for a rather small timeline

Edit: Disregard this, I just updated the jsperf test to use the same selectors for all cases and it turns out that I was wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM