I'm trying to identify why I cannot get my code to work using JavaScript to wrap all of a specific elements inside a specific div. I've read posts like this one but don't understand why it won't work using the query selector.
So i have this HTML:
<div class='containerA'>
<p>random text</p>
</div>
<div class='containerA'>
<p>random text</p>
</div>
Jquery is loaded in the browser, so using a simple select in JS should work but it fails with the error message shown below:
document.getElementsByClassName('containerA')[0].wrap('<div></div>') // fails "document.getElementsByClassName(...)[0].wrap is not a function"
Also, looping through each element to apply to all using JS fails, presumably for the same reason as the first failure above:
// "el.wrap is not a function"
for (var el of els) {
el.wrap('<div class="testWrap"></div>');
}
// "els[i].wrap is not a function"
for (i = 0; i < els.length; i++) {
els[i].wrap('<div class="testWrap"></div>');
}
// "c.wrap is not a function"
els.forEach((el) => el.wrap('<div class="testWrap"></div>'))
But using jQuery I can get the following to work:
works: $('.containerA').wrap('<div class="testWrap"></div>'); // wraps all elements
works: $('.containerA:first-of-type').wrap('<div class="testWrap"></div>'); // wraps specified element
But using query selector doesnt:
document.querySelector('.containerA:first-of-type').wrap('<div class="testWrap"></div>'); // fails with error "document.querySelector(...).wrap is not a function"
So my main questions are:
- How can I wrap individual elements using JS with a loop?
- Why does wrap() apply to all elements when wrapAll() presumably should? (my successful JQ code applies to all elements)
- Why ever use wrapAll() rather than wrap()?
- Presumably wrap() is only for jQuery, but presumably JQ can work with JS, so why wouldn't wrap work after selecting an element using query selector, document get element by class name or any other JS selector?
Any explanation would be much appreciated. Is there something obvious I'm not getting? Thanks for any advice here.