Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create multiple span inside div using javascript

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

        }
like image 919
Dinesh Patil Avatar asked Apr 02 '14 12:04

Dinesh Patil


3 Answers

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

like image 194
Phil H Avatar answered Oct 23 '22 19:10

Phil H


Try like following using jQuery:

$('button').on('click',function (e) {
     $('#demo').append('<span>'+$('textbox').val()+'</span>');
 });
like image 6
Ibrahim Khan Avatar answered Oct 23 '22 18:10

Ibrahim Khan


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

like image 2
Mohd Irshad Avatar answered Oct 23 '22 18:10

Mohd Irshad