0

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

John
  • 7,500
  • 16
  • 62
  • 95
  • yep, pretty easy to do.. just supply some more code, so we can help you with that :) – Walialu Aug 18 '11 at 12:16
  • possible duplicate of [Wrapping an Element using Pure JavaScript !](http://stackoverflow.com/questions/3337587/wrapping-an-element-using-pure-javascript) – pimvdb Aug 18 '11 at 12:16

3 Answers3

3

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);
red
  • 3,163
  • 1
  • 17
  • 16
2
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

jsFiddle

this is the same example within a container

Teneff
  • 30,564
  • 13
  • 72
  • 103
0

here you go:

http://jsbin.com/uyiluf/3

source:

http://jsbin.com/uyiluf/3/edit#source

Alex
  • 3,732
  • 5
  • 37
  • 59
  • 1
    welcome to SO :) Answers containing links to code/examples should also include the linked-to source code. – karim79 Aug 18 '11 at 12:32