CreateElement in jQuery

I work with CreateElemant in JavaScript, this is my code:

function generateInputs() { var i = document.createElement("input"); for(var j=0;j<4;j++) { var c = document.createElement("input"); var r = document.createElement("input"); r.setAttribute('type',"radio"); document.getElementById('questions').appendChild(r); c.setAttribute('type',"input"); document.getElementById('questions').appendChild(c); } i.setAttribute('type',"text"); document.getElementById('questions').appendChild(i); } 

And I want to write it using jQuery, but I did not find an equivalent for createElement ()

+7
javascript jquery
source share
6 answers

Just try:

 function generateInputs() { var i = $('<input type="text"/>'); for(var j=0;j<4;j++) { var c = $('<input type="text"/>'); var r = $('<input type="radio"/>'); $('#questions').append(c).append(r); } $('#questions').append(i); } 
+6
source share
 // $("#id"), $("element") or $(".class") for selecting parent $("#foo").append("<div>hello world</div>") var txt1="<p>Text.</p>"; // Create element with HTML var txt2=$("<p></p>").text("Text."); // Create with jQuery var txt3=document.createElement("p"); // Create with DOM txt3.innerHTML="Text."; $("p").append(txt1,txt2,txt3); // Append the new elements 
+1
source share
 $('<input />').attr('type','radio').appendTo(document.body) 

some like this

0
source share

Do you just want to create new elements on the fly? If so, then you need to do what you need:

 $('<input>').attr({ type: 'hidden', id: 'foo', name: 'bar' }).appendTo('#questions'); 

Obviously change the "type" and "name" to whatever you need.

0
source share

Screenshot

 function generateInputs() { var i = $("<input/>"); //var i = document.createElement("input"); for (var j = 0; j < 4; j++) { var c = $("<input/>", { //document.createElement("input"); type: "radio" //r.setAttribute('type',"radio"); }); var r = $("<input/>", { //document.createElement("input"); type: "radio" //c.setAttribute('type',"radio"); }); $('#questions').append(r);//document.getElementById('questions').appendChild(r); $('#questions').append(c);//document.getElementById('questions').appendChild(c); } i.attr('type', "text"); // i.setAttribute('type',"text"); $('#questions').append(i);//document.getElementById('questions').appendChild(i); } 


A bit shorter code

Demo Screenshot

 function generateInputs() { var i = $("<input/>", { type: "text" }); for (var j = 0; j < 4; j++) { var c = $("<input/>", { type: "radio" }); var r = $("<input/>", { type: "radio" }); $('#questions').append(r, c); } $('#questions').append(i); } 

Learn jQuery

JQuery API documentation

0
source share
 function generateInputs() { var i = $('<input type="text"'); for ( var j = 0; j < 4; j++ ) { var c = $('<input type="input" />'); var r = $('<input type="radio" />'); $('#questions').append(r).append(c); } $(document).append(i); } 
0
source share

All Articles