开发者

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

开发者 https://www.devze.com 2023-01-23 12:52 出处:网络
Have run into jquery question while learning ajax. $(\'div_hello\'); --> answers an \'Object\' document.getElementById(\'div_hello\');

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 h开发者_运维知识库ow a jquery 'Object' differs from an HTML element. How would I ie set the html of the jquery object?

thank you


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.


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


(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!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号