views:

347

answers:

3

Hi there,

I have what I thought was a simple select with jQuery to change some text on a paragraph. It works perfect the traditional way i.e.

document.getElementById('message_text').innerHTML = "hello";

But with jQuery it doesn't. I have checked the values of $('#message_text') and sure enough I see the items.

$('#message_text').innerHTML = "hello";

Am I doing something wrong?

Anyone have any ideas?

+4  A: 

$('#message_text').html('hello')

jQuery selector returns an array, not a DOM Element node.

Eugene Morozov
+5  A: 

The jQuery function $() is not returning a HTMLElement object like getElementById() does but a jQuery object. And there you just have the html() method as equivalent to innerHTML. So:

$('#message_text').html('hello');
Gumbo
+12  A: 

When you do something like $('#message_text') what you have there is not a regular DOM object, but a jQuery wrapped set (even though in this case it'd only be one element.) If you wanted to access a particular DOM property, you could do this:

$('#message_text')[0].innerHTML = 'whatever';
$('#message_text').get(0).innerHTML = 'whatever';

However, this isn't necessary in this case as jQuery has two functions to do what you want:

html():

$('#message_text').html('whatever');

text():

$('#message_text').text('whatever');

The difference between the two is that html() will allow HTML while text() will escape any HTML tags you pass to it. Use the one you need over manually manipulating the HTML with innerHTML.

Paolo Bergantino
Nice of you to give a full explanation, I deleted my simpler, non-explanatory answer, since yours is better.
Jason Bunting
Thanks for a detailed explanation..
mark smith