10

I have one image, when I am clicking on that image, I am getting one textbox and a button. By clicking on button, I want to put that textbox values in separate spans inside a div with id demo. Ho I can do that using javascript only?

Here is the function in which I was trying the same(I am trying so lots of error must be there)

function addTag(){

            var text = document.getElementById('title').value;
            //console.log(text);
            var demoid = document.getElementById('demo');
            console.log(demoid);

            var spa = document.createElement('span');
            spa.id = text;
            spa.appendChild(demoid);
            var text = text+' , ';
            spa.innerHTML = text;
            console.log(spa.id);

            jQuery("#form_panel").hide();
            jQuery("#someID").hide();

            console.log("in addTag");

        }
0

4 Answers 4

12

To create a span element in javascript:

var newSpan = document.createElement('span');

Add it to the DOM tree in the right place, say inside the 'demo' div:

document.getElementById('demo').appendChild(newSpan);

So a textbox in a span in that div:

var newTextbox = document.createElement('input');
newTextbox.type = 'textbox';
var newSpan = document.createElement('span');
var demodiv = document.getElementById('demo');

newSpan.appendChild(newTextbox);
demodiv.appendChild(newSpan);

console.log(demodiv.innerHTML);

Console yields:

<span><input type=\"textbox\"></span>

The alternative is to construct a complete chunk of HTML (performance may vary):

document.getElementById('demo').innerHTML += "<span><input type='textbox'></span>";

-- Edit after seeing your code --

It looks like you are doing spanElement.appendChild(divElement), but that is attempting to insert the div inside the span. You want to insert the span into the div, so you need divElement.appendChild(spanElement).

1
  • I already have text box, and i want to add that text box value in new span in #demo div whenever i will click on button after text box. Commented Apr 3, 2014 at 5:38
6

Try like following using jQuery:

$('button').on('click',function (e) {
     $('#demo').append('<span>'+$('textbox').val()+'</span>');
 });
2

Using the Javascript functions createElement() and appendChild() will work for you.

1

You better use jQuery.

You can use $.add() or $.append() functions.

Visit https://api.jquery.com/append/ for more information.

Hope this will help you!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.