I was trying to validate some URLs. I have tried using regex and JavaScript URL constructors as well. But I was specifically trying to solve the task with document.createElement('a').
I am following the codes for the task and it works fine in JSbin. But not working in my local editor. Can anyone explain if document.createElement('a') is valid for anchor tags and why there is a result in JSbin and not in my local editor(it shows some error).
P.S Working new with JavaSCript and DOM Manipulation
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>test</title>
</head>
<body>
<div id="div"></div>
<script src="test.js"></script
</body>
</html>
JavaScript
function isValidURL(str) {
var div = document.getElementById('div');
var a = document.createElement('a');
a.href = str;
a.innerText = "check";
div.appendChild(a);
return a.protocol === "http:" || a.protocol === "https:";
}
console.log(isValidURL('file:///Y:/bleh/index.html'));
console.log(isValidURL('https://www.youtube.com/watch?v=iFP-EWO_Q_o'));
console.log(isValidURL('en.wikipedia.org'));
The console results false, true, true accordingly in jsbin. But show error ReferenceError: document is not defined in local editor.