开发者

jQuery | Remove li tags

I'm searching a solution to remove <li> tags filtered using javascript array.

var mygroups=["1","8","3","4","5"]

Example (input):

<li><div>1 element. Bla bla bla</div></li>
<li><div>2 element. Bla bla bla. This is my <span>post</span> into new group</div></li>
<li><div>3 element. Bla bla bla. Another one</li>
<li><div><a href="/groups/viewgroup/1-first-group">First group</a></div></li>
<li><div>5 element. Bla bla bla. This is my <span>new post</span></div></li>
<li><div>6 element. <img alt="groups.wall" class="newsfeed-icon" src="/assets/favicon/default.png"></div></li>
<li>7 eleme开发者_开发问答nt.</li>
<li><div><a href="/groups/viewgroup/8-second-group">First group</a></div></li>
<li><div><a href="/groups/viewgroup/16-other-group">First group</a></div></li>
<li><div><a href="/groups/viewgroup/5-tttt-group">First group</a></div></li>

How to get this output (Remove all instances which do not contain mygroups):

<li><div><a href="/groups/viewgroup/1-first-group">First group</a></div></li>
<li><div><a href="/groups/viewgroup/8-second-group">First group</a></div></li>
<li><div><a href="/groups/viewgroup/5-tttt-group">First group</a></div></li>

Thank you!


You really should introduce some kind of flag (a classname for instance or some data- attributes) to identify <li> nodes you don't have to display. Such a verbose check needs to scan the whole HTML for each <li>, which is not a good practice. However, it could look like this:

$('li').each(function(_, node) {
    if( !/group|groups/.test( node.innerHTML ) )
        $(node).remove();
});

Demo: http://jsfiddle.net/zkprg/


EDIT: Updated to match your new requirements.

Updated the jsFiddle example as well.

The jQuery code I used was:

$(function() {
    var mygroups = ["1", "8", "3", "4", "5"];
    $('li').each(function() {
        var $li = $(this);
        // if you only want li's with an <a> link to a group page which matches one
        // in your mygroups list...
        var $a = $li.find('a[href^="/groups/viewgroup/"]');
        // if we find a matching <a> (whose href attribute starts with "/groups/viewgroup/")
        if ($a.length) {
            // extract this <a>'s group number using a regular expression
            var groupNum = $a.attr('href').replace(/^\/groups\/viewgroup\/(\d+)-.+$/gi, '$1');
            // remove the <li> if group number is not in our allowed array
            if ($.inArray(groupNum, mygroups) == -1) $li.remove();
        } else {
            $li.remove(); // no <a> found, so remove this <li>
        }
    });
});

I have tried to comment this to explain most lines, let me know if anything doesn't make sense. You can use this ChopApp page to click on lines and add notes/questions easier than you can in StackOverflow. Just leave me a comment on here if you use that, and I will reply to your questions there.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜