innerHTML in jQuery

Probably one of the more common things you use javascript for is to do simple replacement of text within a DIV. What you may not know is that you can use jQuery to make the command shorter (which makes it easier to type) and you actually can get more functionality than regular javascript.

With traditional JavaScript you would type something like this to change the contents of a DIV tag:

document.getElementById('mydiv').innerHTML = "Hello World";

However with jQuery you can simply type:

$('#mydiv').html("Hello World");

As you can see you had to write less code to do the same thing. As I mentioned previously with jQuery you get more functionality than regular JavaScript. You noticed that we used the selector feature of jQuery in order to make the change. This means you can use a class or any other jQuery selector to change the content of anything in the page.

To change the content of a block that has a certain class you would type:

$('.myclass').html("Hello World");

Now in order to get the contents of any DIV or class or anything else you can select you would use the following code:

var mycontent = $('.myclass').html();

As you can tell using jQuery’s html function you can save yourself a lot of typing as well as give your code more power and flexibility.

Leave a Reply

Your email address will not be published. Required fields are marked *