If I have: <span>Some Code Here</span>
, can I create a new div
element and move the span
element inside just created div
?
The new element must be in same place where span
element was before
I'd like to use pure javascript code
If I have: <span>Some Code Here</span>
, can I create a new div
element and move the span
element inside just created div
?
The new element must be in same place where span
element was before
I'd like to use pure javascript code
HTML:
<span id="the_id">Some code...</span>
JS:
var the_div = document.getElementById('the_id');
var foobar = document.createElement('div');
foobar.appendChild(the_id);
the_id.parentNode.replaceChild(foobar, the_id);
var wrapper = document.createElement('div');
var selected_span = document.getElementByTagName('span')[0]; //get the first available span element
span_clone = selected_span.cloneNode(true);
selected_span.parentNode.insertBefore(wrapper, selected_span);
selected_span.parentNode.removeChild(selected_span);
wrapper.appendChild(span_clone);
What this does is create a new <div>
, creates copy of the span
, removes the original span
and then inserts the copy inside the div
this is the same example within a container