I have such html data:
<div class="class1">...</div>
<div开发者_StackOverflow社区 class="class1 class2">...</div>
<div class="class3">...</div>
...
<div class="class1">...</div>
<div class="class1 class2">...</div>
<div class="class3">...</div>
How can I get divs with class1 and then divs with class2?
I tried such way:
var divs = $(data).find('.class1');
But it returned empty array.
I tried other way:
var divs = $(data).filter('.class1');
But it returned array
[div.class1, div.class1, ..., div.class1].
So, I could not find divs with 'class2' in it, because 'class2' was lost... It's so strange...
Has anybody ideas? Thanks!
When you call filter
on a collection, you get only the elements that match that filter. However, the original collection is not being modified.
All you have to do is store the original collection in a variable, and refer back to that when you want to filter by .class2
:
var all = $(data),
class1 = all.filter('.class1'),
class2 = all.filter('.class2');
$("div[class*='class1']");
To test, run this code:
var divs = $("div[class*='class1']");
divs.each(function() {
alert($(this).text());
});
The reason why find
didn't work is probably because your HTML string doesn't have a root element, so the search is performed inside of each element. If you wrapped the HTML inside of a containing element, find
should work.
精彩评论