Class array
1. Class array definition
// Class array is a special object that looks like an array but is not an array
// Class arrays have two characteristics:
// 1. There is a length attribute
// 2. Index with incrementing positive integers
const brand = {
0: 'HUAWEI'.1: 'APPLE'.2: 'XIAOMI'.length: 3};console.log(brand);
console.log(brand.length);
console.log(brand[0], brand[1], brand[2]);
console.log(Array.isArray(brand)); // false
console.log(brand instanceof Object); // true
Copy the code
- Class array and array difference
// Arrays can use push() to append a member to an array from the tail
// Class array will be error "brand. Push is not a function"
const arr = [1.2.3];
console.log(arr); / / [1, 2, 3]
arr.push(4);
console.log(arr); // [1, 2, 3, 4]
const brand = {
0: 'HUAWEI'.1: 'APPLE'.2: 'XIAOMI'.length: 3}; brand.push("OnePlus"); // "brand.push is not a function"
Copy the code
- Class arrays are converted to real arrays
const brand = {
0: 'HUAWEI'.1: 'APPLE'.2: 'XIAOMI'.length: 3};// Turn the "class array" into a real array, so that we can manipulate it with powerful array methods
// 1. Array.from()
let arr1 = Array.from(brand);
console.log(Array.isArray(arr1)); // true
arr1.push("vivo");
console.log(arr1); // ["HUAWEI", "APPLE", "XIAOMI", "vivo"]
// 2. [...rest]: merge parameter, REST syntax
"Brand is not iterable"
// let arr2 = [...brand]; // "brand is not iterable"
// js creates iterator interfaces for some preset types, but not for custom types
Object.defineProperty(brand, Symbol.iterator, {
value() {
let index = 0;
const keys = Object.keys(this);
return {
next: () = > {
return {
done: index >= keys.length - 1.value: this[keys[index++]], }; }}; }});let arr2 = [...brand];
console.log(arr2, Array.isArray(arr2)); // ["HUAWEI", "APPLE", "XIAOMI"] true
arr2.push('OPPO');
console.log(arr2); // ["HUAWEI", "APPLE", "XIAOMI", "OPPO"]
Copy the code
Get DOM elements quickly
$($); $($);
<body>
<ul class="list">
<li class="item">item1</li>
<li class="item">item2</li>
<li class="item">item3</li>
<li class="item">item4</li>
<li class="item">item5</li>
</ul>
<script>
// $("body"): jQuery uses this syntax to get the 'body' element
let$=selector= > document.querySelector(selector);
console.log($);
console.log($("body"));
// Set the background color for the body
$('body').style.background = "lightcyan";
</script>
</body>
Copy the code
2. Obtain the set of all elements that meet the criteria
<ul class="list">
<li class="item">item1</li>
<li class="item">item2</li>
<li class="item">item3</li>
<li class="item">item4</li>
<li class="item">item5</li>
</ul>
<script>
// Get the set of elements that meet the criteria
const items = document.querySelectorAll(".list .item");
// NodeList: class array
// Iterate over the items element
// NodeList has a forEach() interface
// item: the current element being traversed. This is mandatory
// index: index of the current element
// items: the array object currently traversed
items.forEach(function (item, index, items) {
console.log(item, index, items);
});
// Use arrow function to simplify, use this syntax more in the future
items.forEach(item= > console.log(item));
// Think: how do I get the first element that satisfies the condition?
let firstItem = items[0];
console.log(firstItem);
firstItem.style.background = "lightgreen";
</script>
Copy the code
3. Get the first element in the set of elements that meet the criteria
<ul class="list">
<li class="item">item1</li>
<li class="item">item2</li>
<li class="item">item3</li>
<li class="item">item4</li>
<li class="item">item5</li>
</ul>
<script>
// Get the first element in the set of elements that meet the criteria
firstItem = document.querySelector(".list .item");
console.log(firstItem);
firstItem.style.background = "green";
// querySelector() always returns a unique element, often used with ids
// querySelectorAll, querySelector, can also be used on elements
let list = document.querySelector(".list");
let items = list.querySelectorAll(".item");
console.log(items);
// NodeList uses an iterator interface for traversal
for (let item of items) {
console.log(item);
}
// The following traditional methods are not recommended after ES6
// document.getElementById()
// document.getElementsByTagName()
// document.getElementsByName()
// document.getElementsByClassName()
</script>
Copy the code
4. Get some specific elements quickly
<ul class="list">
<li class="item">item1</li>
<li class="item">item2</li>
<li class="item">item3</li>
<li class="item">item4</li>
<li class="item">item5</li>
</ul>
<form action="" name="hello" id="login">
<input type="email" placeholder="[email protected]" />
<button>submit</button>
</form>
<script>
// Get some specific elements quickly
// body
console.log(document.body);
// head
console.log(document.head);
// title
console.log(document.title);
// html
console.log(document.documentElement);
//forms
console.log(document.forms);
console.log(document.forms[0]);
// <form action="" name="hello" id="login">
console.log(document.forms["hello"]);
console.log(document.forms["login"]);
console.log(document.forms.item(0));
console.log(document.forms.item("hello"));
console.log(document.forms.item("login"));
console.log(document.forms.namedItem("hello"));
// forms.id
// Id is recommended because it is easy to add styles
console.log(document.forms.login);
console.log(document.forms.hello);
</script>
Copy the code
DOM tree traversal and element acquisition
1. Convert the class array to a true array type
<ul class="list">
<li class="item">item1</li>
<li class="item">item2</li>
<li class="item">item3</li>
<li class="item">item4</li>
<li class="item">item5</li>
<li class="item">item6</li>
</ul>
<script>
// Everything in the DOM tree is: nodes
// Nodes are typed: elements, text, documents, attributes...
let nodes = document.querySelector(".list");
console.log(nodes.childNodes);
// Usually only nodes of element type are concerned
console.log(nodes.children);
let eles = nodes.children;
/ / traverse
// Convert the class array to a true array type
console.log([...eles]);
[...eles].forEach(ele= > console.log(ele));
// get the first one
let firstItem = eles[0];
firstItem.style.background = "yellow";
// The last one
// let lastItem = eles[4];
let lastItemIndex = eles.length - 1;
let lastItem = eles[lastItemIndex];
lastItem.style.background = "lightblue";
</script>
Copy the code
2. Use the shortcuts provided by JS to get the first and last
firstElementChild
Get the first onelastElementChild
Get the last one
<ul class="list">
<li class="item">item1</li>
<li class="item">item2</li>
<li class="item">item3</li>
<li class="item">item4</li>
<li class="item">item5</li>
<li class="item">item6</li>
</ul>
<script>
// js provides some shortcuts to get the first and last
const list = document.querySelector(".list");
firstItem = list.firstElementChild;
firstItem.style.background = "seagreen";
lastItem = list.lastElementChild;
lastItem.style.background = "yellow";
console.log(eles.length);
console.log(list.childElementCount);
</script>
Copy the code
3. Obtain sibling nodes
nextElementSibling
Next sibling nodepreviousElementSibling
Previous sibling node
<ul class="list">
<li class="item">item1</li>
<li class="item">item2</li>
<li class="item">item3</li>
<li class="item">item4</li>
<li class="item">item5</li>
<li class="item">item6</li>
</ul>
<script>
// How do I get the second element?
// The second element is the next sibling of the first element
let secondItem = firstItem.nextElementSibling;
secondItem.style.background = "red";
// Get the fifth, which is the previous sibling of the last element
let fiveItem = lastItem.previousElementSibling;
fiveItem.style.background = "cyan";
</script>
Copy the code
Content of DOM elements
<div class="box">
<p></p>
</div>
<script>
const box = document.querySelector(".box");
const p = document.querySelector("p");
// textContent: Add text
p.textContent = "hello world";
// HTML string
p.textContent = '<em style="color:red">php.cn</em>';
// Use innerHTML if you want to render an HTML string
p.innerHTML = '<em style="color:red">php.cn</em>';
// outerHTML: Replaces the current node directly with the text used as the current node (actually the parent of the current content)
p.outerHTML = '<em style="color:red">php.cn</em>';
console.log(box);
</script>
Copy the code
5. Dataset user-defined data attributes
<p id="user" email="[email protected]" data-email="[email protected]" data-my-age="99">My files</p>
<script>
const p = document.querySelector("p");
// id is the default built-in standard property, so it can be accessed directly using dot syntax
console.log(p.id);
// Email is a non-built-in property
console.log(p.email);
// 1. For the user-defined data attribute "data-", use the dataset object to operate
console.log(p.dataset.email);
// console.log(p.dataset["my-age"]);
// 2
console.log(p.dataset.myAge);
</script>
Copy the code
Add, delete, change and check DOM tree elements
1. Create a DOM element and add it to the page display
// Create a DOM element
let div = document.createElement("div");
let span = document.createElement("span");
span.textContent = "hello";
// append(ele,'text'), appends the argument to the list as the last child of the parent element, returns no value
// span is added to div
// div.append(span);
// Add span,"world", to div
div.append(span, " world");
// Add div to the page
document.body.append(div);
console.log(div)
// Method 2: Add span "world" to the page
// document.body.append(span, " world");
// console.log(div)
Copy the code
2. Why did the span in div disappear?
// Why is the span in div missing?
// The new span element can only be inserted in one place; Span in div, now span in body, which is the equivalent of a clipping operation
// If you want to keep span in div, clone span
// cloneNode(true), true: is the complete internal structure of the reserved element
document.body.append(span.cloneNode(true), " world");
Copy the code
The effect is as follows:
3. Add, delete and modify DOM tree elements
append()
: appends to the tailprepend()
: Appends to the headerbefore()
: Adds a new node before the reference pointafter()
: Adds a new node after the reference pointreplaceWith()
: Replace elementsRemove (no parameters)
: Delete elementafterBegin
: The first child after the start tagbeforeBegin
: Starts the tag before its previous sibling elementafterEnd
: After closing the tag, its next sibling elementbeforeEnd
: Terminates the tag before its last child element
// append() creates a list
const ul = document.createElement("ul");
// Loop to generate multiple list items li
for (let i = 1; i <= 5; i++) {
let li = document.createElement("li");
li.textContent = `item${i}`;
ul.append(li);
}
document.body.append(ul);
// append(): appends to the end
// prepend(): appends to the header
li = document.createElement("li");
li.textContent = "first item";
li.style.color = "red";
ul.prepend(li);
// What if I want to add something other than the header and tail?
// There must be a reference node location, otherwise you don't know which node to add to before or after
// Use the fourth node as a reference
const referNode = document.querySelector("li:nth-of-type(4)");
referNode.style.background = "cyan";
// Add a new node before it
li = document.createElement("li");
li.textContent = "Insert before reference node";
li.style.background = "yellow";
// referNode.before(el), called at the insertion position (reference node)
referNode.before(li);
// Add a new node after it
li = document.createElement("li");
li.textContent = "Insert after reference node";
li.style.background = "violet";
// referNode.after(el), called at the insertion position (the reference node)
referNode.after(li);
// Replace the node
// Replace the last node with a link
let lastItem = document.querySelector("ul li:last-of-type");
let a = document.createElement("a");
a.textContent = PHP Chinese Website;
a.href = "https://php.cn";
lastItem.replaceWith(a);
// Delete node, called directly on the deleted node
// delete the sixth ul,remove(no arguments)
ul.querySelector(":nth-of-type(6)").remove();
// Let me introduce some more excellent ones
// insertAdjacentElement(' insert location ', element)
// There are four insertion positions
// afterBegin: The first child element after the start tag
// beforeBegin: Start a tag before its previous sibling
// afterEnd: After the tag ends, its next sibling element
// beforeEnd: Ends the tag before its last child
// Before the first child element is inserted (after the start tag);
li = document.createElement("li");
li.textContent = "First child";
ul.insertAdjacentElement("afterbegin", li);
ul.insertAdjacentElement("beforebegin", li);
// Plus allows you to use HTML strings as elements, eliminating the need to create elements
// append to the end
ul.insertAdjacentHTML("beforeEnd".');
// You can also insert text directly
const h2 = document.createElement("h2");
h2.insertAdjacentText("beforeend", ul.lastElementChild.textContent);
console.log(h2);
document.body.insertAdjacentElement("afterend", h2);
Copy the code
7. CSS operations
1. Inline styles
<p>Hello World</p>
<script>
const p = document.querySelector("p");
// Add inline styles
p.style.color = "red";
console.log(p);
</script>
Copy the code
2. The type of styleclassList
<style>
.bgc-cyan {
background-color: cyan;
}
.bgc-yellow {
background-color: #ff0;
}
.border {
border: 3px solid # 000;
}
.bolder {
font-weight: bolder;
}
</style>
<p>Hello World</p>
<button id="btn" onclick="toggleBorder">Switch bezel</button>
<script>
const p = document.querySelector("p");
// add() adds styles. Multiple styles can be added simultaneously
p.classList.add("bgc-cyan");
p.classList.add("border"."bolder");
// remove() removes styles
p.classList.remove("border");
// replace() replace style
p.classList.replace("bgc-cyan"."bgc-yellow");
btn.onclick = function () {
// toggle: Toggle automatically. If it already exists, remove it. If it doesn't, add it.
p.classList.toggle("border");
};
// Only one style can be added to className at a time. It is not recommended
// p.className = "bgc-yellow";
// p.className = "bgc-yellow border";
</script>
Copy the code
3. Calculation style
<div style="height: 50px; background-color: #ff0; color: red">Hello World</div>
<script>
const div = document.querySelector("div");
// The browser decides how an element should be rendered
// The browser calculates the final style based on an element's inline style, internal style, and external style sheet
// getComputedStyle(to view styled elements, pseudo-elements)
let styles = window.getComputedStyle(p, null);
// Get background color, different browsers get different, Chrom browser error
// let styles = document.defaultView.getComputedStyle("p", null);
// The computing styles are read-only
// console.log(styles);
console.log(styles.getPropertyValue("height"));
console.log(styles.getPropertyValue("background-color"));
console.log(styles.getPropertyValue("color"));
</script>
Copy the code