How do I move all the li elements with specific css style to another ul?
I need to move all of the <li style="display:none;">
under a particular <ul id="bob">
开发者_如何学JAVAinto a different <ul id="cat">
. In performing this move, I need all the classes, ids, and css styling to be preserved, and obviously the content as well.
Easy one-liner:
$('#bob > li:hidden').appendTo('#cat');
will move all ul#bob > li
which are hidden, which is a superset of ul#bob > li
which have style="display:none;"
, since:
Elements can be considered hidden for several reasons:
- They have a CSS
display
value ofnone
.- They are form elements with
type="hidden"
.- Their width and height are explicitly set to 0.
- An ancestor element is hidden, so the element is not shown on the page.
http://api.jquery.com/hidden-selector
If you really want only those elements whose style
attribute is display: none;
, I'd do it with .filter()
and a regexp:
var pattern = /^\s*display:\s*none\s*;?\s*$/gi;
$('#bob > li').filter(function ()
{
return pattern.test($(this).prop('style'));
}).appendTo('#cat');
The regexp is case- and (mostly) whitespace-insensitive, and allows the semicolon to be optional, which is valid CSS. If you don't care about either of those you can git-r-dun with a one-liner, as before:
$('#bob > li[style="display:none;"]').appendTo('#cat');
$('#cat').append($('#bob > li').filter(':hidden').remove());
$('#bob li:hidden').remove().end().appendTo('#cat');
精彩评论