开发者

Creating parent child element using DOM

开发者 https://www.devze.com 2023-01-16 23:41 出处:网络
I want to create the following DOM structure using jQuery. <li> <label> user <input type=radio>

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 th开发者_Python百科ere is something wrong, what would be best practice here?


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'));


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.


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


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())

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号