Cannot add HTML code in single div using jQuery

I have one div id = userinfo

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

And now I want to add something to this div, depending on localStorage.

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

But this failed, regardless of whether I injected this script into a separate JS file or added them to the header of the html file. I tried to eliminate this using the Google Developer Console for Chrome, it works as expected.

I tried again changing the script to:

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

And add this to the js file, it works!

So now I'm complicated, why is my jQuery code not working?

+3
source share
3 answers

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

+1
source

Using jquery we can do it below

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

0
source

Source: https://habr.com/ru/post/1777007/


All Articles