2

it appears that when I call the if (test.href != "https://www.test.com") it gives me a null value, but I'm not exactly sure why, as I'm expecting it to return the URL

HTML

<p><a id="damn" href="https://www.test.com" target="_self">PC Install</a></p>

JS SCRIPT:

var test= document.getElementById("damn");
if (test.href != "https://www.test.com") {console.log(test)}
Jack Bashford
  • 38,499
  • 10
  • 36
  • 67
John Mckhay
  • 47
  • 1
  • 7

2 Answers2

1

Use getAttribute, and it works.

var test = document.getElementById("damn");
if (test.getAttribute("href") != "https://www.test.com") {
  console.log(test)
}
<p><a id="damn" href="https://www.test.com" target="_self">PC Install</a></p>
Jack Bashford
  • 38,499
  • 10
  • 36
  • 67
  • Hi Jack, it seems like I'm still getting this error: Uncaught TypeError: Cannot read property 'getAttribute' of null – John Mckhay Feb 15 '19 at 07:59
  • It works in the snippet though - make sure your JS isn't running before your HTML. – Jack Bashford Feb 15 '19 at 08:00
  • Oh, I see. So I have to put my script at the end of my JS. That was probably my issue. I really appreciate the help, super thankful, I just joined stackoverflow, seems pretty handy! – John Mckhay Feb 15 '19 at 08:03
  • No problem @JohnMckhay, if my answer fixed your problem please mark it as accepted by clicking the grey tick mark to the left of my answer to turn it green. – Jack Bashford Feb 15 '19 at 08:03
0

try to reorder your code, and let your script after the 'a' tag.

陈杨华
  • 445
  • 3
  • 9