Click here to Skip to main content
15,902,893 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to parse data from an HTML file using DOMParser(). This is the file's structure:

HTML
...
<p>text to ignore</p>
<p>text to ignore</p>
<p>text to ignore</p>
<br/>
<p>text to ignore</p>
<p>text to ignore</p>
<p>text to ignore</p>
<br/>
<p>text to parse</p>
<p>text to parse</p>
<p>text to parse</p>
...

How can I get the index of last "br/" tag, in order to parse all the "p" elements after it?

What I have tried:

JavaScript
var doc = new DOMParser().parseFromString(file, "text/html");
var LastBrIndex = doc.lastIndexOf("<br/>");


TypeError: doc.lastIndexOf is not a function
Posted
Updated 10-Aug-23 6:36am
v2

Assuming all of the elements are siblings, as shown in your question, then you can use the :last-of-type[^] selector to find the last <br> element, and then iterate over its following siblings.

For example:
JavaScript
const doc = new DOMParser().parseFromString(file, "text/html");
const lastBr = doc.querySelector("br:last-of-type");

const elementsToProcess = [];
let el = lastBr ? lastBr.nextElementSibling : doc.firstChild;
while (el) {
    if (el.tagName === "P") { elementsToProcess.push(el); }
    el = el.nextElementSibling;
}
Demo[^]
 
Share this answer
 
See Document - Web APIs | MDN[^] for valid methods to access the HTML DOM.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900