I have many divs with there IDs being in a simple order like: div1 , div2, div3, div4 and so on. The HTML code is:
<div id='div1'>..abc..</div>
<div id='div2'>..def..</div>
<div id='div3'>..ghi..</div>
<div id='div4'>..jkl..</div>
<div id='div5'>..mno..</div>
They all contain different piece of text inside them. And now i want to sort the div in which the length of text inside is equal to 15. To do so i suppose there are two methods:
I used separate analysis js code:
<script>
var div1 = document.getElementById('div1');
var div2 = document.getElementById('div2');
var div3 = document.getElementById('div3');
var div4 = document.getElementById('div4');
var div5 = document.getElementById('div5');
if (div1.value.length = 50){
alert('div 1 sorted');
}
//like this for all of them
</script>
I did like this for all five of them. till here it was fine but now i have to do this for suppose 100 div's so i tried using loop here:
<script>
var i = 0;
while (i <= 100){
var allDiv = 'div' + i;
if(allDiv.value.length == 50){
alert(allDiv+' sorted')
}
i += 1;
}
</script>
But this didn't work. I think when if function is taking allDiv.value as [div+i] here like div1. How to make it object? also please suggest any changes which i should make.
Use a for loop
In each iteration, get the div from the DOM
Check the value and length with innerText
Alert if your condition is met
for (let i = 1; i < 6; i = i + 1) {
const div = document.getElementById('div' + i);
if (div && div.innerText.length === 15) {
alert(`div ${i} has a length of 15`);
}
}
<div id='div1'>aaaaa</div>
<div id='div2'>bbbbb</div>
<div id='div3'>ccccccccccccccc</div>
<div id='div4'>ddddd</div>
<div id='div5'>eeeee</div>
An even cleaner solution
if you want to do it in an easier way and you can change the HTML. I would add a class to each div in order to select them all at one go and loop through them. That way you also don't have to know how many divs are on the page immediately:
const allDivs = document.querySelectorAll('.div-to-select');
allDivs.forEach(div => {
if (div.innerText.length === 15) {
alert(`div with id ${div.id} has length 15`);
}
});
<div id='div1' class="div-to-select">aaaaa</div>
<div id='div2' class="div-to-select">bbbbb</div>
<div id='div3' class="div-to-select">ccccccccccccccc</div>
<div id='div4' class="div-to-select">ddddd</div>
<div id='div5' class="div-to-select">eeeee</div>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments