最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check if a value already exists on a <li> tag with jQuery - Stack Overflow

programmeradmin6浏览0评论

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!

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!

Share Improve this question asked Oct 7, 2011 at 19:36 pmerinopmerino 6,13011 gold badges60 silver badges77 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 8
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 parison 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)

  1. 暂无评论