I'm trying to make a function that -
Grabs all the links on a page, Compares those links with a link that the user inputs, and Checks if the link already exists on the page
It seems like I can get the value from the input box, and have converted the links into an array. However, even though I match the values (E.g. http://www.test.com/), the .includes function keeps returning false.
I've tried converting the array to a string. That worked, but it compared everything, and not the specific links. (E.g. Even if I just put "h" into the input box, it would say there's a duplicate link.)
<!DOCTYPE html>
<html>
<head>
</head>
<body>
URL: <input id="URL" type="text" name="URL"><br>
<input onClick="grabLinks()" type="submit" value="Submit">
<div id="dupliURLNum">0</div>
<script>
function grabLinks() {
//Get URL from input
var URL = document.getElementById('URL').value;
//Get all links
var links = document.querySelectorAll('a');
//Convert Nodelist to Array
var linksArr = Array.from(links);
//Compare Link to Array
var compareArr = linksArr.includes(URL);
alert(URL);
alert(linksArr);
alert(compareArr);
if (compareArr === true) {
alert('Duplicate');
}
else {
alert('NoDuplicate');
}
};
</script>
<a href="http://www.test.com">test</a>
<a href="https://stackoverflow.com">stackoverflow</a>
<a href="https://www.ford.com">ford</a>
</body>
</html>
The expected result would be a user types "http://www.test.com" into the input box. Then compareArr would return true.
If they type in a link that isn't on the page, compareArr would return false.
The actual result is that it always returns false.
I've added alerts just for debugging purposes.
var linksArr = Array.from(links)converts all theaelements to URLs ready for comparison?HTMLLinkElementis not astring! They can never be===(that's the comparison thatArray#includesdoes). Better dolinksArr.some(a => a.href === URL);