Pramendra Gupta
Pramendra Gupta

Reputation: 14873

Creating parent child element using DOM

I want to create the following DOM structure using jQuery.

<li>
  <label> user
    <input type=radio>
  </label>
</li>

Here is my jQuery.

$('<input>')
.attr({type:'radio'})
.appendTo($('<label>'))
.text('user')
.appendTo($('<li>'))

Some how it's not working or there is something wrong, what would be best practice here?

Upvotes: 2

Views: 595

Answers (4)

bevacqua
bevacqua

Reputation: 48566

use $('input') instead of $('<input>'), same with label and li,

Upvotes: 1

Reigel Gallarde
Reigel Gallarde

Reputation: 65274

your problem is this,

$('<input>')
.attr({type:'radio'}) // until this line, input type radio was created as expected.
.appendTo($('<label>')) // you have created label and append the radio button to it.
.text('user') // the problem here, is .text() is referring to $('<input>'), and not the label.
.appendTo($('<li>')) // and you append the radio in a dynamically created li...

I think you have just missed the logic. Try this,

var $li = $('<li>');
var $label = $('<label>').text('user');
var $radio = $('<input>').attr({type:'radio'});

$label.append($radio).appendTo($li);
$li.appendTo('#ULId');

if you want to chain everything, then do it this way,

$('<label>').text('user')
.append($('<input type="radio">'))
.appendTo($('<li>').appendTo('#someULid'));

Upvotes: 3

Sergey
Sergey

Reputation: 12437

You can just create the whole thing from a string:

var $mynode = $("<li><label> user <input type=radio></label><li>");

or create several nodes and then combine them:

var $input = $("<input type=radio>");
var $label = $("<label> user </label>");
var $li = $("<li />");

$label.append($input);
$li.append($label);

My point is, your code is chained to the point that it's very hard to read and understand it.

Upvotes: 2

lock
lock

Reputation: 6614

You don't actually have to put the tags in the selector function

for example your code in append should just be appendTo($('li'))

furthermore, it's best if you had id attributes for your elements if you need to manipulate them with jquery DOM otherwise all LI's on your page would be affected when you run that code.

that is more visible on the part where you append it to label, it would be nice if you can just specify appendTo($('li#my_list li').first())

Upvotes: 0

Related Questions