Если я правильно понимаю ваш вопрос, это можно сделать с помощью поля .nextSibling
на узлах DOM.
Это позволит вам получить доступ к следующему узлу-брату к текущему обрабатываемому узлу (т.е. первый элемент p
в вашем документе).Вы можете использовать это для перебора всех допустимых братьев и сестер, поиска любого с innerText
, соответствующего вашим критериям и добавления их в список извлеченных узлов, например:
var extracted = [];
/*
Get starting node for search. In this case we'll start
with the first p element
*/
var p = document.querySelector('p');
/*
Iterate through each sibiling of p
*/
do {
/*
If this sibling node has innerText that matches the
number pattern required, add this node to the list of
extracted nodes
*/
if(p.innerText && p.innerText.match(/\d+./gi)) {
extracted.push(p.innerText);
}
/*
Move to next sibling
*/
p = p.nextSibling;
}
while(p) /* Iterate while sibing is valid */
console.log('Extracted plain text for nodes with number string for innerText:', extracted);
<p>1.</p>
<h1>This is the first paragraph..</h1>
<button>click</button>
<p>2.</p>
<h3>And this is the second...</h3>
<img src="" alt="" />
<p>3.</p>
<h5>this is the last paragraph</h5>