I need to select text between any two given HTML nodes (in the order thats visible to user).
As an example in following screenshot(
Edit:
In another works I am looking for completion of this function
// firstElement and secondElement don't need to be related.
// They dont be part of same subtree
function getBetweenElements(firstElement, secondElement) {
...
return result;
}
CodePudding user response:
function getBetweenElements(firstElement, secondElement) {
let result = [];
let nextEl = firstElement.nextElementSibling;
while (nextEl !== secondElement) {
result.push(nextEl);
nextEl = nextEl.nextElementSibling;
}
return result;
}
console.log(
getBetweenElements(
document.getElementById("first"),
document.getElementById("second"),
),
);
<p id="first">hello 1</p>
<p>my 1st paragraph</p>
<p>my 2nd paragraph</p>
<p>my 3rd paragraph</p>
<p>my 4rd paragraph</p>
<p>my 5rd paragraph</p>
<p id="second">hello 2</p>
the idea:
- get the next element after the first selected element using
Element.nextElementSibling
Notice they have no
id
or class selector in particular that is helpful. They're just plain<p>
s.So, something like this should work:
const answer = document.getElementById("answer"); const els = Array.from(answer.childNodes); // filter out the 'text's const pEls = els.filter((el) => (el.nodeName === "P")); const answers = pEls.filter(pEl => (pEls.indexOf(pEl)%2 !== 0)); // do whatever with the answers console.log(answers.map(ans => ans.innerText.trim()));
<div style="color:#232F3E;" id="answer"> <p><b>Q: Can I really set up Amazon Connect in minutes?</b></p> <p>Yes. We encourage you to go to the <a href="https://console.aws.amazon.com/connect/home">Amazon Connect console</a> and set up an Amazon Connect contact center now.</p> <p><b>Q: Do you have examples of how customers are already using Amazon Connect?</b></p> <p>Yes. Please see the <a href="/connect/customers/">Amazon Connect customers</a> web page and the <a href="https://aws.amazon.com/blogs/contact-center/">AWS contact center blog channel</a>.<br> </p> </div>
CodePudding user response:
I think this will help you solve your problem :
<!-- common section using html --> <section id="mySection"> <h2>first title</h2> <div>first div</div> <h2>secund title</h2> <div>secund div</div> <h2>third title</h2> <div>third div</div> </section> <script> // Defining a variable to put the extracted texts inside const myItems = [] // Select the section using javascript const fatherElement = document.getElementById("mySection") // Here we make a loop on the children of the section for (const children of fatherElement.children) { // And if the son has a specific tag, we extract the text from inside it and put it in the variable of the extracted texts if (children.tagName === "DIV") { myItems.push(children.innerText) } } console.log(myItems); // ['first div', 'secund div', 'third div'] </script>
We can also use the id of the element instead of the tag name or any other distinctive detail of the elements we want