我使用 JS 創建了一個包含其所有內容的部分。
const main = document.querySelector('main') ,
new_p = document.createElement('p'),
new_h2 = document.createElement('h2'),
new_div = document.createElement('div'),
new_section = document.createElement('section')
main.appendChild(new_section);
new_section.id = ('section4');
new_section.appendChild(new_div);
new_div.classList.add('landing__container');
new_div.appendChild(new_h2);
new_div.appendChild(new_p);
new_h2.textContent = 'Section 4';
new_h2.id = 'heading4';
new_p.textContent = 'some text goes here'
然后我制作了所有部分的陣列(以前使用 HTML 創建,新創建使用 JS)。
const sections = Array.from(document.getElementsByTagName("section"))
問題是陣列只獲取僅用 HTML 創建的部分,而看不到用 JS 創建的部分。
這是記錄到控制臺的陣列(陣列中的 3 個專案已經用 HTML 創建了)
(3) [section#section1.your-active-class, section#section2, section#section3]
任何人都可以幫助我如何使用 JS 檢測新創建的部分?
uj5u.com熱心網友回復:
我測驗了這段代碼,它正在作業。JS在這里沒有問題。也許您正在嘗試在添加新部分之前訪問部分。看到這個片段:
const main = document.querySelector('main') ,
new_p = document.createElement('p'),
new_h2 = document.createElement('h2'),
new_div = document.createElement('div'),
new_section = document.createElement('section')
main.appendChild(new_section);
new_section.id = ('section4');
new_section.appendChild(new_div);
new_div.classList.add('landing__container');
new_div.appendChild(new_h2);
new_div.appendChild(new_p);
new_h2.textContent = 'Section 4';
new_h2.id = 'heading4';
new_p.textContent = 'some text goes here'
const sections = Array.from(document.getElementsByTagName("section"))
console.log(sections);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- <script type="module" src="./async-await.js"></script> -->
<script type="module" src="./script.js" defer></script>
</head>
<body>
<main>
<section id="section1"></section>
<section id="section2"></section>
<section id="section3"></section>
</main>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/366742.html
標籤:javascript 数组
上一篇:將兩個陣列合并為一個物件
