[英]DOM Methods get the right element from a Node - Using only JavaScript
I am doing an exercise, but I am stuck.我正在做运动,但我被卡住了。 I need to get the first line of each paragraph after each "H4", but at the moment it is getting all the "P" from the first "H4".我需要在每个“H4”之后获取每个段落的第一行,但目前它正在从第一个“H4”中获取所有“P”。
I got an HTML and a JavaScript, the idea is to get a news summary after Bizarre News Summary , I have created the 'UL', 'LI' and appended them我有一个 HTML 和一个 JavaScript,这个想法是在Bizarre News Summary之后获得一个新闻摘要,我创建了“UL”、“LI”并附加了它们
function newsSnippets() { let classNewsarticle = document.getElementsByClassName("newsarticle"); // Get classes by name 'newsarticle' let headlinesId = document.getElementById("headlines"); // Get Id 'headlines' let newsSummary = document.createElement("div"); // Create DIV headlinesId.appendChild(newsSummary); // Append headlines to DIV let newsSummaryList = document.createElement("ul"); // Create UL newsSummary.appendChild(newsSummaryList); // Append UL to DIV console.log(classNewsarticle); for (let i = 0; i < classNewsarticle.length; i++) { let newsSummaryListItem = document.createElement("LI"); // Create an LI for each H4 newsSummaryList.appendChild(newsSummaryListItem); // Append the LI to the UL let getH4 = document.getElementsByTagName("H4")[i].childNodes[0].nodeValue; let getH4Node = document.createTextNode(getH4); let ellipsis = document.createTextNode(". . . "); let p = document.getElementsByTagName("P")[i].innerHTML; let pNode = document.createTextNode(p); newsSummaryListItem.appendChild(getH4Node) + // Append the texts node to the LI element newsSummaryListItem.appendChild(ellipsis) + newsSummaryListItem.appendChild(pNode); let newsList = document.createElement("LI"); // Create the inline text anchor document.body.insertBefore(newsList, newsSnippets[i]); // Insert the text anchor before headings } } window.onload = newsSnippets;
<.doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>JavaScript</title> <link rel="stylesheet" type="text/css" href="styles/styles.css"> <script src="scripts/fma_t1.3,js"></script> </head> <body> <div id="wrappermain"> <h1>Bizarre News Mash Up</h1> <section id="headlines"> <h2>Bizarre News Summary</h2> </section> <section id="news"> <h3>News Stories in Full</h3> <article class="newsarticle"> <h4>What a load of Bull.</h4> <p>Chinese Kung Fu Masters are seeking the ultimate opponents</p> <p>Several times a week, kung fu teacher Ren Ruzhi enters a ring to spar with a bovine opponent around five times his weight and capable of killing him.</p> <p>Ren's mixing of martial arts and bullfighting worries his mother, but the 24-year-old has never been hurt, Besides. he says, grappling with a snorting bull is exciting.</p> <p>It symbolizes the bravery of a man?” Ren told Reuters in Jiaxing in China's eastern province of Zhejiang.</P> </article> <article class="newsarticle"> <h4>Has Anybody got a Tissue,</h4> <p>A Hawaiian monk seal got an eel caught in its nose ― and it wasn't the first time for these endangered creatures.</p> <p>The Hawaiian Monk Seal Research Program posted a startling pic of the poor pup on Monday. and the National Oceanic and Atmospheric Administration Fisheries provided more details in a post on Wednesday.</p> </article> <article class="newsarticle"> <h4>Dog Pulls Off Spectacular Save During Argentina Soccer Match</h4> <p>A pooch invaded the pitch during a Federal A league match between Juventud Unida and Defensores de Belgrano over the weekend.</p> <p>Juventud Unida were already comfortably ahead against Defensores de Belgrano in their league clash when the dog made his unexpected cameo,</p> </article> <article class="newsarticle"> <h4>Nobody Beats The Laws of Nature</h4> <p>A 69-year-old Dutch man has failed in his attempt to legally declare himself 20 years younger,</p> <p>Last month, motivational speaker Emile Ratelband filed a lawsuit against the Dutch government requesting that his date of birth be switched from March 11, 1949. to March 11. 1969.</p> </article> </section> </div> <!-- Stories from Huffington Post. Used for Teaching purposes --> </body> </html>
This seems a little too complicated.这似乎有点太复杂了。 If you are allowed to, try something like this:如果允许,请尝试以下操作:
function newsSnippets() {
const results = document.evaluate('//article[@class="newsarticle"]', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
let temp = "<div><ul>"
for (let i = 0; i < results.snapshotLength; i++) {
let node = results.snapshotItem(i);
let new_item = "<li>"+node.querySelector('h4').innerText+ '...' +node.querySelector('p').innerText+"</li>";
temp += new_item;
}
temp += "</ul></div>"
let target = document.querySelector('section#headlines');
target.insertAdjacentHTML('beforeend', temp);
}
I was able to came up with an answer myself and it works just fine.我自己想出了一个答案,而且效果很好。
function newsSnippets() {
let classNewsarticle = document.getElementsByClassName("newsarticle"); // Get classes by name 'newsarticle'
let headlinesId = document.getElementById("headlines"); // Get Id 'headlines'
let newsSummary = document.createElement("div"); // Create DIV
headlinesId.appendChild(newsSummary); // Append headlines to DIV
let newsSummaryList = document.createElement("ul"); // Create UL
newsSummary.appendChild(newsSummaryList); // Append UL to DIV
for (let i = 0; i < classNewsarticle.length; i++) {
let newsSummaryListItem = document.createElement("LI"); // Create an LI for each H4
newsSummaryList.appendChild(newsSummaryListItem); // Append the LI to the UL
let getH4 = document.getElementsByTagName("H4")[i]; // Get H4s
let getH4Text = getH4.childNodes[0].nodeValue; // Get H4s Nodes
let getH4Node = document.createTextNode(getH4Text); // Get H4s HTML Text
let ellipsis = document.createTextNode(" . . . "); // Create Text Node Ellipsis
let p = getH4.nextElementSibling.innerHTML; // Get P as the Next Element Sibling from each H4
let pText = document.createTextNode(p); // Create Text Node for each first P after H4
newsSummaryListItem.appendChild(getH4Node) + // Append the textNodes to the LI element
newsSummaryListItem.appendChild(ellipsis) +
newsSummaryListItem.appendChild(pText);
}
}
window.onload = newsSnippets;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.