I have a piece of HTML:
<a name="list">the list</a>
<ul>
<li><a href="http://google.com">http://google.com</a></li>
<li><a href="/tutorial">/tutorial.html</a></li>
<li><a href="local/path">local/path</a></li>
<li><a href="ftp://ftp.com/my.zip">ftp://ftp.com/my.zip</a></li>
<li><a href="http://nodejs.org">http://nodejs.org</a></li>
<li><a href="http://internal.com/test">http://internal.com/test</a></li>
</ul>
and a piece of JS:
let links = document.querySelectorAll('a');
for (let link of links) {
let href = link.getAttribute('href');
alert(href.includes("://"))
The question is why the JS above doesn't work (it should display true/false), but works if I add an if-condition:
let links = document.querySelectorAll('a');
for (let link of links) {
let href = link.getAttribute('href');
if (!href) continue;
alert(href.includes("://"))
It doesn't work when you didn't add if statement because there is a case href returns null for the link list you are trying.
For your information, I share the console.log message when it doesn't work.
VM260:4 Uncaught TypeError: Cannot read properties of null (reading 'includes')
at <anonymous>:4:14
If you add if statement, then the includes is not executed in the code snippet. Hope that's clear to you.