1

I've "cached" a jQuery object that I use inside a loop called $myElement. I would like to use some native JavaScript functions on it (for better performance). However, my attempts below throws errors (the element is undefined). Is there any way to accomplish this?

$myElement.find('span')[0];

$myElement.find('span').get(0);

Update: What Im trying to do is something like:

$myElement.find('span')[0].innerHTML('some text');

That's giving me an error.

5
  • 6
    What you typed is valid. We probably need more code to see your error. Commented Oct 15, 2012 at 13:50
  • Your syntax should be working: jsfiddle.net/mHUNU Commented Oct 15, 2012 at 13:51
  • @dystroy Ok, please have a look at my update Commented Oct 15, 2012 at 13:52
  • Which element is inside the jQuery object $myElement? Is the span itself in there or a parent of it? If the span is already in the object you could also use filter(), which doesn't read the DOM but only the objects contents. Commented Oct 15, 2012 at 13:55
  • @Johan You didn't posted any updates… Commented Oct 15, 2012 at 13:56

3 Answers 3

6

You seem to need

$myElement.find('span')[0].innerHTML = 'some text';

Because innerHTML isn't a function on basic DOM elements.

But there is nothing wrong, if you get your element using jQuery, to also use the html function :

$myElement.find('span').first().html('some text');

I don't think you're optimizing at the right point.

Sign up to request clarification or add additional context in comments.

5 Comments

or $myElement.find('span')[0].html('some text')if jQuerys abstraction is OK
no ... .html() can only be used on jQuery objects, but find('span')[0] isn't
@devnull69 He didnt say that. Neither is he using the html() method on the dom element
@Johan I think that devnull69 was speaking of the comment from mariusnn
but @mariusnn is ... my comment was referring to his/her comment
3

The .innerHTML property is not a function. Just set its content using assignment.

.innerHTML = "foo";

But be careful with .innerHTML when using jQuery. If you clear content like that, and any of that content has any data or handlers assigned with jQuery, you'll have a memory leak.

A safer practice would be to use jQuery to update content.

.html("foo");

Comments

0

You can use jQuery's "first" function like this:

$myElement.find('span').first();

Or use to get an nth-child by an index using jQuery's "eq" function, like this:

$myElement.find('span').eq(3);

Or you can also use jQuery's "get" function to return a DOM instance of that match:

$myElement.find('span').get(2);

As you can see on this example:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.