Properly selecting and filtering elements in variable HTML structure with jQuery
I have a HTML fragment with multiple elements (mostly of the same type (here for example I use SPAN), but also a few others) that may be enclosed within a DIV, but not always. Basically, sometimes I have a single root element (the DIV), sometimes I have multiple elements at the same level. What is the proper way to select all of these specified elements (SPAN) with jQuery?
Clarification Update: This way of selecting should succeed for both cases listed below
To give an example, the following code segment shows you two possible structures for my HTML fragment.
var test1 = "<div><span></span><span></span>开发者_JAVA技巧;<div></div></div>";
var test2 = "<span></span><span></span><div></div>";
alert($(test1).filter("span").length);
alert($(test2).filter("span").length);
Naturally, the first filter returns 0, whereas the second returns 2. I know one way to 'solve' this would be to encapsulate my fragment within a DIV, on which I then run my filter, however I'm curious to know if there's a better solution.
Update 2: What I could do (as mentioned in the paragraph above) is something like the following code, which works for both cases:
alert($("<div></div>").append(test2).find("span").length);
If you wanted to find out how many spans are contained in a element you would use
.siblings()
so say you have this:
<div><span></span><span></span><div></div></div>
if you want to see how many spans are contained in the div you would
$('div').siblings("span").length;
and if you just wanted to know how many elements are contained in that div you would just remove the parameter from siblings like this:
$('div').siblings().length;
精彩评论