3

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?

Daniel Chen
  • 1,933
  • 5
  • 24
  • 33
  • 1
    I tried it and it works. Can you reproduce the error on a [jsfiddle](http://jsfiddle.net/)? – cambraca Nov 26 '10 at 05:08
  • 6
    Did you tried your code placing inside $(document).ready(function() {});? – Asif Mulla Nov 26 '10 at 05:09
  • 1
    Hi Asif Mulla, thanks for your hint. It works after I placing them inside $(document).ready(function(){}); if you want, you can post this as an answer :-) – Daniel Chen Nov 26 '10 at 05:24

3 Answers3

1

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>'))

Ghyath Serhal
  • 7,466
  • 6
  • 44
  • 60
0

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

Aleks Felipe
  • 1,922
  • 2
  • 14
  • 14
0

Using jquery we can do like this below

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

Kumar
  • 214
  • 2
  • 7