Reputation: 23791
I'm trying to dynamically create a check box inside a div using javascript.Here is a part of my code
var input = document.createElement('input');
input.setAttribute('id', 'chkFilm_1');
input.setAttribute('type', 'checkbox');
input.setAttribute('name', 'four');
input.setAttribute('style', 'margin-left:2px;');
var divFilm = document.createElement('div');
divFilm.className = "ChekMarkWrap";
divFilm.appendChild(input);
divFilm.appendChild(document.createElement('br'));
divFilm.innerText = "film";
What i'm trying to achieve is inserting the check box before the div's innerText.But the text always comes after the div innerText.
Upvotes: 1
Views: 1020
Reputation: 2375
Try appending checkbox after appending div , Try this:
divFilm.parentNode.insertBefore(input, divFilm);
Upvotes: 0
Reputation: 3556
how about this:
divFilm.innerHTML = divFilm.innerHTML + input.outerHTML+"film" ;
or even shorter:
divFilm.innerHTML += input.outerHTML+"film" ;
Upvotes: 0
Reputation: 105
It looks like your problem could be the line:
divFilm.innerText = "film";
which would replace the divFilm text instead of appending to it.
The following code seems to work
var input = document.createElement('input');
input.setAttribute('id', 'chkFilm_1');
input.setAttribute('type', 'checkbox');
input.setAttribute('name', 'four');
input.setAttribute('style', 'margin-left:2px;');
var divFilm = document.getElementById("film")
divFilm.appendChild(input)
divFilm.appendChild(document.createElement('br'));
divFilm.innerHTML += 'film';
This adds these elements to a div in your html with id "film".
This is working in the following link http://jsfiddle.net/yeQeC/
Upvotes: 2