Native approach
document.getElementsByClassName('words')[0].getElementsByTagName('br').length
Native approach
document.getElementsByClassName('words')[0].getElementsByTagName('br').length
You could count the number of newlines in the text representation of your node (found via innerText
property), or count the number of <br>
tags with jQuery:
$('.words').each(function() {
// count newlines
const lines = (this.innerText.match(/n/g) || '').length
console.log(lines);
// or, count tags
console.log($('br', this).length);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="words-container">
<div class="words">
here are words<br>
here are words<br>
here are words<br>
here are words<br>
</div>
</div>
Note that I’m doing a .each()
here, because $('.words')
doesn’t strictly resolve to just one element, it’s a group of elements.
In order the find the number of tags, I use the initialiser variant with context to select the <br>
tags inside of this
(which is each element with words
class.
If you just want to count direct descendent <br>
elements inside all parents with word
class, you’d do
$('.words > br').length
Please checkout this.
<div class="words-container">
<div class="words">
here are words<br>
here are words<br>
here are words<br>
here are words<br>
</div>
</div>
<script>
$countWords = $('.words-container')
if ($countWords.length) {
var hahaha = $('.words').find('br').length
alert(hahaha)
}
</script>
Like this:
console.log($('.words-container .words br').length) // 4
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="words-container">
<div class="words">
here are words<br>
here are words<br>
here are words<br>
here are words<br>
</div>
</div>
Let’s say I have:
<div class="words-container">
<div class="words">
here are words<br>
here are words<br>
here are words<br>
here are words<br>
</div>
</div>
Using Javascript or jQuery, how would I count the exact amount of <br>
tags that are populated in the “words” div? I need a way to know how many lines there are.
Not sure what I’m doing here:
$countWords = $('.words-container')
if ($countWords.length) {
var hahaha = $('.words').find('<br>').length
console.log(hahaha.length)
}
$('.words').find('br').
You’ve called
I know you’ve followed the title, but the question does just state:
@RoryMcCrossan Updated with a way to count tags as well.
That’s true, but I’d still recommend counting the value from the source, instead of the browsers interpretation of the text created from the source