如何通过document.querySelector依次查找多个<br>?
How to find multiple <br> in sequence via document.querySelector?
如果我有多个 <br>
的序列,我该如何显示我有多少个序列?
换句话说,我正在计算我们有多少次 <br><br>
连续两次
。
// Undesired output:
console.log(document.querySelectorAll('br').length) // 8
console.log(document.querySelectorAll('br+br').length) // 7
<div id="test">
Paragraph 1
<br>
<br>
Paragraph 2
<br>Paragraph 2 continued
<br>
<br>
Paragraph 3
<br>Paragraph 3 continued
<br>
<br>
Paragraph 4
</div>
期望的输出:
console.log(document.querySelectorAll('?????').length) // 3
您可以使用正则表达式查找 <br><br>
s:
var p = /<br>[\r\n]*<br>/g;
console.log([...document.querySelector('#test').innerHTML.matchAll(p)].length); // => 3
<div id="test">
Paragraph 1
<br>
<br>
Paragraph 2
<br>Paragraph 2 continued
<br>
<br>
Paragraph 3
<br>Paragraph 3 continued
<br>
<br>
Paragraph 4
</div>
试试这个:
var nodes = document.querySelectorAll('br, div');
console.log(nodes);
<div id="test">
Paragraph 1
<br>
<br>
Paragraph 2
<br>Paragraph 2 continued
<br>
<br>
Paragraph 3
<br>Paragraph 3 continued
<br>
<br>
Paragraph 4
</div>
我想不出更好的方法,希望这对您有所帮助!
const brTags = document.querySelectorAll('br')
let tagCount = 0;
for(let i = 0; i < brTags.length; i++){
const string = brTags[i].nextSibling.textContent
.replaceAll("\n", "")
.trim();
if(string.indexOf("Paragraph") > -1 && string.length === 11){tagCount++}
}
console.log ("Tag count: ", tagCount);
<div id="test">
Paragraph 1
<br>
<br>
Paragraph 2
<br>Paragraph 2 continued
<br>
<br>
Paragraph 3
<br>Paragraph 3 continued
<br>
<br>
Paragraph 4
</div>
如果我有多个 <br>
的序列,我该如何显示我有多少个序列?
换句话说,我正在计算我们有多少次 <br><br>
连续两次
。
// Undesired output:
console.log(document.querySelectorAll('br').length) // 8
console.log(document.querySelectorAll('br+br').length) // 7
<div id="test">
Paragraph 1
<br>
<br>
Paragraph 2
<br>Paragraph 2 continued
<br>
<br>
Paragraph 3
<br>Paragraph 3 continued
<br>
<br>
Paragraph 4
</div>
期望的输出:
console.log(document.querySelectorAll('?????').length) // 3
您可以使用正则表达式查找 <br><br>
s:
var p = /<br>[\r\n]*<br>/g;
console.log([...document.querySelector('#test').innerHTML.matchAll(p)].length); // => 3
<div id="test">
Paragraph 1
<br>
<br>
Paragraph 2
<br>Paragraph 2 continued
<br>
<br>
Paragraph 3
<br>Paragraph 3 continued
<br>
<br>
Paragraph 4
</div>
试试这个:
var nodes = document.querySelectorAll('br, div');
console.log(nodes);
<div id="test">
Paragraph 1
<br>
<br>
Paragraph 2
<br>Paragraph 2 continued
<br>
<br>
Paragraph 3
<br>Paragraph 3 continued
<br>
<br>
Paragraph 4
</div>
我想不出更好的方法,希望这对您有所帮助!
const brTags = document.querySelectorAll('br')
let tagCount = 0;
for(let i = 0; i < brTags.length; i++){
const string = brTags[i].nextSibling.textContent
.replaceAll("\n", "")
.trim();
if(string.indexOf("Paragraph") > -1 && string.length === 11){tagCount++}
}
console.log ("Tag count: ", tagCount);
<div id="test">
Paragraph 1
<br>
<br>
Paragraph 2
<br>Paragraph 2 continued
<br>
<br>
Paragraph 3
<br>Paragraph 3 continued
<br>
<br>
Paragraph 4
</div>