I have 5 div elements 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:
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:
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,
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