GarryRig
GarryRig

Reputation: 135

jquery not working to change inner html?

hey people I'm new at jquery and i have been trying to figure this out for like the past couple of hours... what the hell am I doing wrong here? All I want to do is change the innerHTML of a div.

$("left_menu_bar").innerHTML = "You clicked me!";

but the div doesn't change at all when I call the function with that code init.

Upvotes: 10

Views: 18615

Answers (4)

jessegavin
jessegavin

Reputation: 75650

You're attempting to assign some text to a property named innerHTML on an object that doesn't have a property named innerHTML.

The $ function in jQuery doesn't return a DOM element. It returns a jQuery object which provides the ability to execute all the wonderful jQuery functions on set particular DOM elements.

One of the functions the jQuery object exposes is .get() which will return one of the elements it contains.

So in your case, you could do:

// 0 means it will return the first element in the jQuery object
$("left_menu_bar").get(0).innerHTML = "You clicked me!";

Or as @helmus stated in his answer, you could use the .html() function that jQuery provides to set the content which actually uses innerHTML on the inside.

Upvotes: 3

rjz
rjz

Reputation: 16510

jQuery always returns a jQuery collection--not a DOM element. In order to access DOM properties directly, you'll need to retrieve an element from the collection:

$(".left_menu_bar").first().innerHTML = "You clicked me!";

This isn't very convenient, however, and helmus's answer describes the way that things are usually done.

Upvotes: 5

j08691
j08691

Reputation: 207901

Since left_menu_bar isn't an element, you can't select it that way.

If it's the ID of an element, try:

$("#left_menu_bar").html("You clicked me!");

If it's the class of an element, try:

$(".left_menu_bar").html("You clicked me!");

Upvotes: 2

Willem D'Haeseleer
Willem D'Haeseleer

Reputation: 20180

Do it like this:

// referencing by id
$("#left_menu_bar").html("You clicked me!");
// referencing by class name ( will apply to all div's with this class )
$(".left_menu_bar").html("You clicked me!");

http://api.jquery.com/html/

Upvotes: 20

Related Questions