I have 5 div
e开发者_StackOverflow社区lements with attribute data-role="content"
I select all of them by
a = $('div[data-role=content]')
It returns [object HTMLDivElement]
.
To hide all the div
elements, I iterate through a
and hide each element
<script>
$.each(a, function(index, value) {
if (value) {
alert(typeof(value));
value.hide();
}
})
</script>
But it returns an error ....
TypeError: Result of expression 'a.hide' [undefined] is not a function
On the other hand, if I select a single div with the id:
a = $('div[id=content1]')
it gives me an:
[object Object]
The hide function a.hide()
works in that case.
The question is: "How can I select all the [object Object]
elements at once?" or,
"How can I convert [object HTMLDivElement]
to [object Object]
?"
You're really just looking for this:
var a = $('div[data-role=content]');
a.hide();
You don't need to explicitly iterate over every element in the jQuery object because .hide()
will take care of that for you.
N.B. $.each()
is for iterating over any array-like object. When you're already working with a jQuery object, though, use .each()
instead of $.each()
.
Also, it looks like you're using an attribute selector to select elements by ID. This is a silly way to select elements, as there's a much simpler — and potentially much faster — ID selector. Here's the swap:
$('div[id=content1]') // Change this
$('div#content1') // to this
You can do even better, though, because element IDs must be unique, which means that specifying an ID and an tag name is unnecessarily specific. So,
$('div#content1') // Change this
$('#content1') // to this
Okay, so I couldn't resist following up on this whole ID selector bit to prove just how much faster a solo ID selector is. In my tests: an order of magnitude. http://jsperf.com/jq-id-selectors
The value passed to each
is the actual DIV element itself, not a jQuery wrapped instance of the DIV. DIV elements don't have a hide method. You can use @Matt's suggestion which is the correct and shortest way since the .hide()
call will be applied to all members of the $(...)
result set. Or turn your value into a real jQuery selector with $(value).hide()
.
You're looking for
a.each(function(index, item){
$(this).hide;
});
That is the each that foreaches through a jquery object and actually makes "this" available.
精彩评论