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.
const fruit = "apple"; fruit.contains("a");
"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
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
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
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.