简体   繁体   中英

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".

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

 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM