Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure javascript method to wrap content in a div

I want to wrap all the nodes within the #slidesContainer div with JavaScript. I know it is easily done in jQuery, but I am interested in knowing how to do it with pure JS.

Here is the code:

<div id="slidesContainer">     <div class="slide">slide 1</div>     <div class="slide">slide 2</div>     <div class="slide">slide 3</div>     <div class="slide">slide 4</div> </div> 

I want to wrap the divs with a class of "slide" collectively within another div with id="slideInner".

like image 208
Squadrons Avatar asked Jul 27 '11 00:07

Squadrons


People also ask

How do you wrap an element in JavaScript?

How to use document. createElement() to create an element, and wrap it around each selected element. Using a function to specify what to wrap around each selected element.

Can an A tag wrap a div?

Using this as a example. Yes, putting an anchor around a block is valid in HTML5 specs. Try cutting and pasting the script into the free online validator or pasting the link to your web page.

Can you wrap a around div?

A <div> is not allowed within an <a> elements, as <a> element is of a phrasing content element type according to w3.org/TR/html5/dom.html#phrasing-content-1 which means that only elements of the phrasing content 1 is guaranteed to work inside an <a> element.

What is wrap in JavaScript?

Wrapping JavaScript functions lets you add common logic to functions you do not control, like native and external functions. Many JavaScript libraries, like the TrackJS agents, need to wrap external functions to do their work.


1 Answers

If your "slide"s are always in slidesContainer you could do this

org_html = document.getElementById("slidesContainer").innerHTML; new_html = "<div id='slidesInner'>" + org_html + "</div>"; document.getElementById("slidesContainer").innerHTML = new_html; 
like image 79
Michal Avatar answered Oct 01 '22 23:10

Michal