Author -  Sai gowtham

How to Solve getAttribute is not a Function in JavaScript

In this tutorial, we are going to learn about how to solve the TypeError: getAttribute is not a function in JavaScript.

When we call a ‘getAttribute()’ method on a value, which is not a valid dom element we will get the following error in our console or calling the getAttribute method on a jQuery Object .

Here is an example, how the error occurs:

<h1 id="heading">How are you<h1>
const h1 = null;

h1.getAttribute("id");

Output:

"TypeError: getAttribute is not a function

In the example above, we are getting the error because we are using the ‘getAttribute()’ method on null data type, but the getAttribute() method is only available on a dom element.

To solve the “TypeError: getAttribute is not a function”, make sure to call the getAttribute() method on a valid element.

Here is an example:

<h1 id="heading">How are you<h1>
const h1 = document.getElementById('heading');
const attribute = h1.getAttribute("id");

console.log(attribute);

Output:

"heading"

In the example above, we have called the getAttribute() method a valid dom element. So that, it returns the string representation of the atttribute value for the dom element.

Type checking

To avoid the run time errors, we can also check if the given datatype is a dom element or not before calling the getAttribute() method on it.

Here is an example:

const h1 = null ;

if(typeof value === 'object' && value !== null && 'getAttribute' in h1){
    console.log(h1.getAttribute("id"))
}else{
    console.log('Given value is not a dom element');
}

Conclusion

The “TypeError: getAttribute is not a function” error occurs, when we call a getAttribute() method on a value which is not DOM element. To solve the error, make sure to use the getAttribute() method on a valid dom elements.

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY