[JS] How to check if conditions in loop are finished throught all items - and then do something in a loop?

javascript

(spamator12) #1

Cause the working example is really complicated lets suposse we just… testing page links (or any html element on a page). I simply don’t know how to check if ALL items meet the condition in the loop and if yes, perform an action. More in comments.

HTML:

<html>
<head>
<title>Links test</title>
</head>
<body>
	<!-- links are random - we do not know how many they are, and how many of them got title attribute -->
	<a href="https://www.google.com" title="google">google</a>
	<a href="https://facebook.com/">facebook<</a>
	<a href="https://www.instagram.com/" title="instagram">instagram</a>
	<a href="https://www.amazon.com/">amazon</a>
	<a href="https://www.apple.com/" title="apple">apple</a>
</body>
</html>

JS:

let links = document.getElementsByTagName('a');
let linksLength = links.length;
let titleCount = 0;

for (i = 0; i < linksLength; i++) { // main loop throught ALL links
	if (links[i].getAttribute('title') !== undefined) { // condition that check title attribute
		titleCount += 1; // this is cause I need to count all loop part that fulfil the condition
		// NOW if it's the last item that fulfil this condition then do something (in this main loop) - how to check it?
	}
}