Breaking down the challenge
1. Create a
div with the class of
wrapper and add it to the document body:
This first part shouldn't be too much trouble and here are the three lines of code we'll use:
const wrapper = document.createElement('div'); wrapper.classList.add('wrapper'); document.body.appendChild(wrapper);
2. Make an unordered list containing three list items, and place this list inside the wrapper.
This next step isn't too tricky either. We'll make use of backticks to make creation quick and easy:
const list = ` <ul> <li>list item one</li> <li>list item two</li> <li>list item three</li> </ul> `;
Now we'll add those contents inside the wrapper:
wrapper.innerHTML = (list);
3. Using an HTML string, create another div with two paragraphs inside of it.
We already know how to do this, repeat the process above:
const div = ` <div class="paragraphs"> <p>Paragraph One</p> <p>Paragraph Two</p> </div> `;
4. Now insert this new div before the unordered list from above.
And this is where things got tricky for me..........
We now need to insert the variable div (with the two paragraphs) adjacent to (before) the variable list. My go to solution was to use
insertAdjacentHTML(), but that won't work.
list content we created earlier in our code is a string, not HTML. That means we can't target it with this method...... yet.
The way I went about solving this was by creating another variable
const listElement = document.querySelector('ul');
querySelector() method will target the
ul inside the list string and the new variable
listElement (we could have called it whatever we like) will hold valid HTML elements that will work alongside
Now we can set about targeting the UL element, then placing our paragraphs div alongside using insertAdjacentHTML().
insertAdjacentHTML() takes in two parameters for the insertion point: ('location' and the insertion). We wanted to insert the paragraphs before the list so we used
beforebegin as our insertion point.
The range of location options are:
- beforebegin = before element
- afterbegin = before first child of element
- beforeend = after last child of element
- afterend = after element
MDN Web Docs insertAdjacentHTML
Top comments (0)