Daniel Chen
Daniel Chen

Reputation: 2023

Can't append HTML code into one div by using jQuery

I have one div id=userinfo

<html>
<head></head>
<body>
<div id=userinfo></div>
</body>
</html>

And now I want to append something into this div, depending on the localStorage.

if (localStorage==0){$("#userinfo").append("<p>Test</p>");} else {$("#userinfo").append("<p>Hello</p>");}

But it failed, no matter I input this script into separate JS file or add them into the head of the html file. I tried exclude this with Google chrome developer tool's console, it works as expected.

I've tried another way round change the script into:

if (localStorage==0){alert("Test");} else {alert("Hello");}

And add this into JS file, it works!

So, now I'm stacked why my jQuery code not work?

Upvotes: 3

Views: 7294

Answers (3)

Kumar
Kumar

Reputation: 214

Using jquery we can do like this below

$( "<p>Test</p>" ).appendTo( "#userinfo" );

Upvotes: 0

Ghyath Serhal
Ghyath Serhal

Reputation: 7632

The jquery append function takes an object as parameter and not a string html. So this should solve your problem, $("#userinfo").append($('<p>Test</p>'))

Upvotes: 1

Aleks Felipe
Aleks Felipe

Reputation: 1932

You might have conflicts with other javascript libraries. Try to check out http://docs.jquery.com/Using_jQuery_with_Other_Libraries

Upvotes: 0

Related Questions