// import
import { $, $all } from './ext/Node_ext.js'; // Node extension
import { } from './ext/Iterable.js'; // Iterable extension
import { } from './js/Node_methods.js'; // Node custom methods
// -----------------
// 1. insert before
// -----------------
// all paragraphs
let p = document.body.$all("p");
// ⭐️ insert p[2] before p[0]
document.body.insertBefore(p[2], p[0]);
// Three
// One
// Two
// -----------------
// 2. replace child
// -----------------
// event handler
$('button').onclick = function replaceImages() {
// get all image nodes
// node list returned from `querySelectorAll` is NOT live.
let images = $all("img");
// ☢️ Alert❗
// The loop starts at the end of the list. This is necessary if
// the `images` node list is "live".
for (let i = images.length - 1; i >= 0; i--) {
let image = images[i];
if (image.alt) {
let text = document.createTextNode(image.alt);
// ⭐️ replace (image) child with text node.
image.parentNode.replaceChild(text, image);
}
}
};
// -------------------
// 3. create element
// -------------------
// creates an element node and treats the rest of its arguments
// as children to that node.
function elem(type, ...children) {
// ⭐️ create element
let node = document.createElement(type);
// ⭐️ append children
for (let child of children) {
if (typeof child === "string") child = document.createTextNode(child);
node.appendChild(child);
}
// return element
return node;
}
// add <footer> into <blockquote>
$("#quote").appendChild(
elem("footer",
"— ",
elem("strong", "Karl Popper"),
", preface to the second edition of ",
elem("em", "The Open Society and Its Enemies"),
", 1950"
)
);
// -------------------
// 4. attributes
// -------------------
$all('p')
.filter(p => p.getAttribute('data-classified') === 'secret')
.forEach(p => p.remove()); // ⭐️ remove node