<html>
<head>
<title>Site Title</title>
</head>
<body>
<h2>Actions</h2>
<div class="actions">
<button onclick="modify()">Modify second list item</button>
<button onclick="insertEnd()">Insert fourth list item</button>
<button onclick="insertBetween()">Insert paragraph element between the existing ones</button>
</div>
<hr>
<div class="main-body">
<h1>Article Heading</h1>
<p>The second list item will change 5 seconds after the page loads. Refresh the page to see it again if you missed it.</p>
<p>Some more text</p>
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ul>
</div>
<div class="footer">
<p>Site created by Zach</p>
</div>
</body>
</html>
.actions {
display: flex;
}
.actions button {
margin: 3px;
}
.actions button:hover {
cursor: pointer;
}
function modify() {
const list = document.querySelector('ul');
// Remember, arrays are "zero-indexed"
const secondListItem = list.children.item(1);
secondListItem.textContent = 'a new value';
}
function insertEnd() {
const list = document.querySelector('ul');
const newItem = document.createElement('li');
newItem.textContent = 'new item';
list.appendChild(newItem);
}
function insertBetween() {
// Step 1: Find the element we want to insert something after
const mainBody = document.querySelector('.main-body');
const pItems = mainBody.querySelectorAll('p');
const secondParagraphElem = pItems.item(1);
// Step 2: Create the element we want to insert
const newElem = document.createElement('p');
newElem.textContent = 'some inserted text';
// Step 3: Insert the element
mainBody.insertBefore(newElem, secondParagraphElem);
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.