Here is the HTML:
<div>
<h3>text</h3>
</div>
<div>
<h3>moretext</h3>
</div>
<div>
<h3>123</h3>
</div>
Here is the JS:
var rv1_wlength = $("div").filter(function() {
return $(this).find("h3").filter(function () {
return $(this).text() != "123";
}).length;
});
var rv1_wolength = $("div").filter(function() {
return $(this).find("h3").filter(function () {
return $(this).text() != "123";
});
});
var rv2 = $("div").find("h3").filter(function() {
return $(this).text() != "123";
});
alert(rv1_wlength.text()); // text
// moretext
alert(rv1_wolength.text()); // text
// moretext
// 123
alert(rv2.text()); // textmoretext
I don’t understand why the first two methods print the elements on each line, whereas the second method concatenates them. rv2 is a jQuery object. Then, what are the first two (rv1_wlength and rv1_wolength)?
Furthermore, I don’t understand why the inclusion of the length property makes all the difference in filtering the elements. The second method does nothing, since it returns all the elements. The first method, with the only change being the addition of the length property, correctly filters the elements. I would very much like a line-by-line explanation.
I would sincerely appreciate any feedback. Thank you.
This code gets all div elements containing at least one
h3whose text is not"123".This code is useless:
That will return the original selection,
$('div'), since the callback function always returns a truthy value (an empty jQuery set is still considered truthy).Finally, this code gets all h3 elements whose text is not
"123":When you call
.text(), jquery concatenates the text of all the elements in the selection. In the first case, this is concatenating the text inside the divs, which contains line breaks. In the second, it is concatenating the text in the h3s which do not.