Question

Hello everybody

I am having a problem with adding elements to <li> from jquery,

this is my jquery code

$(".div1").on('click','li',function(){
        var phonenumber = $(this).text();
        $("#phones ul").append("<li>"+phonenumber+"</li>");
    });

but when click on the div1 nothing happend, what am i doing wrong please?

note

when i alter phonenumber i got the information that i need.

edit

    <div class="div1">
<li>press here to show your phone number</li>    
<div id="phones">
<ul>

</ul>
</div>
</div>
Was it helpful?

Solution

I guess what you are suffering from is not putting your code inside the $(document).ready() method.

Change your jQuery code to look like this:

$(document).ready(function () {
    $(".div1").on('click', 'li', function () {
        var phonenumber = $(this).text();
        $("#phones ul").append("<li>" + phonenumber + "</li>");
    });
});

OTHER TIPS

Your HTML should be this:

<div class="div1">press here to show your phone number</div>
<ul id="phones">
</ul>

Then you can do:

$(".div1").on('click', function(){
    var phonenumber = $(this).text();
    $("#phones").append("<li>" + phonenumber + "</li>");
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top