Javascript – jquery changing innerhtml of a P isn’t working

javascriptjquery

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?

Best Solution

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.