javascriptjquerydomcreateelementjquery-attributes

How to create elements of form using jquery


My code is

    <!DOCTYPE html>
    <html>
    <head>
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">                  </script>
    <script>
    function afterText() {
        var txt3 = document.createElement("b");   
        txt3.innerHTML = $("<input/>", {
        type: 'text',
        id: 'vname',
        name: 'name',
        placeholder: 'Your Name'
     });
     $("img").after(txt3);      
    }
    </script>
     </head>
  <body>
    <img src="/images/home.gif" alt="home" width="100" height="140">
    <button onclick="afterText()">click</button>
  </body>
  </html>

The output I got is [object Object]. But how can I add the input field(Append should not be used).


Solution

  • There is no need to mix jQuery and pure JavaScript approaches for DOM manipulation.

    Just use the following:

     $('<div>' +
         '<input type="text" id="vname" name="name" placeholder="Your Name">' +
       '</div>').insertAfter('img');
    

    Or if you need it more advanced:

     $('<div>').append($('<input>', {
        type: 'text',
        id: 'vname',
        name: 'name',
        placeholder: 'Your Name'
     })).insertAfter('img');