Conor Conor - 5 months ago 13
jQuery Question

How to create div with different class on button click?

I was creating a html that would create a div and copy the things in input to that div with a button click.

Like this:

HTML

<input type="text">
<button>Copy</button>
<p></p>


Script

$('button').click(function() {
var div = document.createElement('div');
$('p').append(div);
$('div').html($('input').val());
});


At it worked perfectly

And then i added class to it.

It looks like this:

$('button').click(function() {
var div = document.createElement('div');
div.className = "Someclass";
$('p').append(div);
$('div').html($('input').val());
});


It worked fine as well. But when i click the button it copies the text to all the div's Instead of a single one

How can i create a button that creates different div with different class and which copies text from
<input>
to the newly created div


I found on net that i can use the
i++
thing in javascript for different class.

But that code is not working properly. Please tell me what is the mistake here.

My code looks like this:

$('button').click(function() {
var i = 0;
var div = document.createElement('div');
div.className = "Someclass" + i++;
$('p').append(div);
$('div').html($('input').val());
});

hsh hsh
Answer
  1. take out i from click event
  2. select new div with its corresponding class name .Someclass[i]

change your code like this:

var i = 0;
$('button').click(function() {

    var div = document.createElement('div');
    div.className = "Someclass" + i;
    $('p').append(div);
    $('.Someclass' + i).html($('input').val());
    i++;
});
Comments