Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery $('<div></div>') doesn't create proper div element

I have the following js code:

$(document).ready(function() {
    $(".button").bind("click", function() {
        var div = $('<div></div>');
        $(".label").append(div);
        div.html($(".textField").val());
        console.log(div);
    });
});

with html:

<input type="text" class="textField"/>
<input type="button" class="button" value=" &gt;&gt;"/>
<div class="label" style="color: red;"></div>

and when I click the button, nothing happens. Console output shows that created div is not a proper div object.
But when I copy onclick function handler code into browser console and run it, it works properly.
Here is jsFiddle.
What is wrong here?

like image 591
Chechulin Avatar asked May 05 '26 08:05

Chechulin


1 Answers

Change your Code
JQuery

$(document).ready(function() {
            $(".button").on("click", function() {
                var div = "<div class='id-of-div'></div>"; //changes
                $(".label").append(div);
                div.html($(".textField").val());
                console.log(div);
            });
        });

HTML

<input type="text" class="textField"/>
    <input type="button" class="button" value=" &gt;&gt;"/>
<div class="label" style="color: red;"></div>

I Think, This is helpful

like image 151
Keerthivasan Avatar answered May 10 '26 12:05

Keerthivasan