Gary
Gary

Reputation: 251

jquery $ 'Object' compared to getElementById() element?

Have run into jquery question while learning ajax.

$('div_hello'); --> answers an 'Object'

document.getElementById('div_hello'); --> answers an 'HTMLDivElement'

getElementById works ($ does not). For this experiement, I simply want to use innerHTML.

Not clear on how a jquery 'Object' differs from an HTML element. How would I ie set the html of the jquery object?

thank you

Upvotes: 0

Views: 356

Answers (3)

Gary
Gary

Reputation: 251

(formatted text this time)

Thank you much all,

A lot of wheel-spinning last night and you cleared it up in 5 mins -

works: $('#div_hello').html("

Hello World

");

fails: $('div_hello').html("

Hello World

");

Need the "#"

I wonder why w/o the "#" it didn't blow up (result was nop).

Thank you!

Upvotes: 0

Pekka
Pekka

Reputation: 449435

Not clear on how a jquery 'Object' differs from an HTML element.

A jQuery object is in fact completely different from the underlying DOM element. They are not interchangeable.

You should use the framework's native functions when dealing with $() objects, as Nick shows in his answer.

If you need to access the underlying element though, you can do so using

$('#div_hello')[0].innerHTML

Upvotes: 2

Nick Craver
Nick Craver

Reputation: 630419

You can use .html() like this:

$('#div_hello').html("content")

Or get the DOM element and use .innerHTML, like this

$('#div_hello')[0].innerHTML = "content";
//or
$('#div_hello').get(0).innerHTML = "content";

Note that your selector should be '#div_hello' like I have above, #id selectors are prefixed with a #, otherwise it's an element selector (and looking for a <div_hello> element).

The jQuery object is just a wrapper, it contains an array of references to DOM elements that it acts on, so think of it as "on top of" the DOM element. This is why [0] gets the element directly, because that element is first in the array that your selector found.

Upvotes: 5

Related Questions