Author -  Sai gowtham

How to solve contains is not a function in JavaScript

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

When we use a contains() method on a value which is not an valid HTML DOM node, we will get the following errors in our console.

Example:

const fruit = "apple";
fruit.contains("a");

Output:

"TypeError: fruit.contains is not a function

In the example above, we are checking if the character "a" is available in a string or not using contains() method, so we are getting the error in our console because the contains() only available for HTML dom nodes.

To solve the error, use the includes() method to check if a value is available or not in a strings or arrays.

Here is an example:

const fruit = "apple";
const result = fruit.includes("a");

console.log(result); // true

For arrays:

const arr = [2, 3, 4];
const result = arr.includes(3);

console.log(result); // true

Using contains method for dom nodes

To check if a dom node is available in a document or not, we can use the contains() method in JavaScript.

Here is an example, that checks if a header dom node is present in the document or not.

const header = document.getElementById("header");

console.log(document.contains(header)); // true

Conclusion

The “contains is not a function” error occurs when we call a contains() method on a value other than the dom nodes. To solve the error use includes() method for strings and arrays.

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