Reputation: 4282
I have this:
console.log($("div[id^='highc']"));
This prints me an array of objects. I can easily get what I want by typing:
console.log($("div[id^='highc']")[0]);
Now, $("div[id^='highc']").append('text')
appends to all of the objects in a returned array. How can I assign to a certain object IN the array?
This didn't work:
$("div[id^='highc'][0]").append('text')
Upvotes: 3
Views: 53
Reputation: 241078
It's important to note that $("div[id^='highc']")
returns a jQuery object that contains a collection of DOM elements (if anything is selected). Since jQuery objects are similar to arrays, $("div[id^='highc']")[0]
will return the first DOM element in the jQuery object.
The issue that you're likely experiencing is that you can't use jQuery methods (like .append()
) on native DOM elements. In other words, if you are chaining the .append()
method on the first DOM element in the jQuery object (i.e., $("div[id^='highc']")[0].append(...)
), you will receive an error stating that .append()
is not a function:
Uncaught TypeError:
$(...)[0].append
is not a function
Since the .append()
methods operates on a jQuery object, you could use the .eq()
method in order to retrieve a jQuery object containing the element based on its index.
$("div[id^='highc']").eq(0).append('Text');
Alternatively, an uglier approach would be to wrap the DOM element with $()
in order to return a jQuery object:
$($("div[id^='highc']")[0]).append('Text');
Side note:
In your question you used both $("div[id^='highc'][0]")
and $("div[id^='highc']")[0]
. I'm assuming it was a typo and you meant the latter since $("div[id^='highc'][0]")
wouldn't return any elements due to the fact that the elements probably don't have a [0]
attribute. You probably attempted to use the .append()
method with [0]
outside of the selector.
Upvotes: 1
Reputation: 3814
Your problem is that when you tried $("div[id^='highc'][0]").append('text')
, you put the [0]
inside the selector rather than outside it. The correct code is $("div[id^='highc']")[0].append('text')
Upvotes: 2