inko94
January 17, 2017, 4:58am
1
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?
inko94
January 17, 2017, 5:04am
3
<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
inko94
January 17, 2017, 5:10am
5
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
inko94
January 17, 2017, 5:16am
7
Thank You. It’s working now. sorry I’m a newbie
1 Like
that doesn’t make much sense. JavaScript let’s you access these attributes directly.
var attrib = document.getElementById("anchor").href;
system
Closed
April 18, 2017, 3:35pm
9
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.