Javascript getAttribute not working?

I’ve a simple program where I want to get the href attribute of anchor tag using javascript getAttribute. It generates error on console Uncaught TypeError: Cannot read property ‘getAttribute’ of null but when I copy the javascript code from code editor into browser console it works fine. I don’t know why this is happening?

P.S it also works fine on jsfiddle

Hi inko94 welcome to the forum

Without seeing any of your code I can only guess.

You are running the JavaScript before the DOM has loaded in?

	<a href="www.google.com" id="anchor">Google</a>
var b= document.getElementById("anchor");
var attrib=b.getAttribute("href");
console.log(attrib);

And that JavaScript is at the bottom of the page just before the </body> tag?

1 Like

No it’s included in external javascript file.

That’s why.

When the JavaScript runs, there is no page to “get” anything from yet.

Try moving it from the <head> to just before </body>

1 Like

Thank You. It’s working now. sorry I’m a newbie :expressionless:

1 Like

that doesn’t make much sense. JavaScript let’s you access these attributes directly.

var attrib = document.getElementById("anchor").href;

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.