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"
.
I like to manipulate dom elements directly - createElement, appendChild, removeChild etc. as opposed to the injection of strings as
element.innerHTML
. That strategy does work, but I think the native browser methods are more direct. Additionally, they returns a new node's value, saving you from another unnecessarygetElementById
call.This is really simple, and would need to be attached to some type of event to make any use of.
jsFiddle
Maybe that helps your understanding of this issue with vanilla js.
From what I understand @Michal 's answer is vulnerable to XXS attacks (using innerHTML is a security vulnerability) Here is another link on this.
There are many ways to do this, one that I found and liked is:
This works well. However for me, I sometimes want to just wrap parts of an element. So I modified the function to this:
I hope this helps.
wrapInner multiple tag content
Link Demo Jsbin
A general good tip for trying to do something you'd normally do with jQuery, without jQuery, is to look at the jQuery source. What do they do? Well, they grab all the children, append them to a a new node, then append that node inside the parent.
Here's a simple little method to do precisely that:
And here's how you use it:
If you patch up document.getElementsByClassName for IE, you can do something like:
Example: http://jsfiddle.net/GkEVm/2/
Like BosWorth99, I also like to manipulate the dom elements directly, this helps maintain all of the node's attributes. However, I wanted to maintain the position of the element in the dom and not just append the end incase there were siblings. Here is what I did.