I know how to do this with jQuery, but I want to learn it with vanilla javascript, I have a feeling it’ll be faster. Here’s a link to jsFiddle with a stripped down version of what I’m trying to do. http://jsfiddle.net/yramagicman/MyM2B/ and below is the offending script.
<script>
var id = 'ul';
var tag = 'li';
var wrapTag = 'span';
var wrapper = document.createElement(wrapTag);
var z = document.getElementById(id);
var y = z.getElementsByTagName(tag);
var count = y.length;
for (var i = 0; i < count; i++) {
y[i].setAttribute("class", "red"); //so I can see the result
wrapper.appendChild(y[i].cloneNode(true));
y[i].parentNode.replaceChild(wrapper, y[i]);
wrapper.setAttribute('class', 'hi'); //so I can see the result
}</script>
<!-- and the html-->
<ul id="ul" class="ul">
<li class="li">1</li>
<li class="li">2</li>
<li class="li">3</li>
<li class="li">4</li>
<li class="li">5</li>
<li class="li">6</li>
<li class="li">7</li>
<li class="li">8</li>
</ul>
I can wrap the entire Ul in a div or span or whatever just fine but when I try to wrap each list item I get the error “HIERARCHY_REQUEST_ERR: DOM Exception 3: A Node was inserted somewhere it doesn’t belong.” Any ideas?
You are building an invalid DOM.
<li>must belong in<ul>or<ol>but you’re trying to place it in a<span>. Hence the error: “A Node was inserted somewhere it doesn’t belong”.