开发者

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 o开发者_C百科n the the <ul>with the timeline id? Thanks!


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


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

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜