Ошибка document getelementbyid is not a function

I’m learning jQuery and was following a tutorial, a very strange error has perplexed me.
Here’s my html :

<!doctype html>
<html>
  <head>
    <title> Simple Task List </title>
    <script src="jquery.js"></script>
    <script src="task-list.js"></script>
  </head>

  <body>
    <ul id="tasks">

    </ul>
      <input type="text" id="task-text" />
      <input type="submit" id="add-task" />
  </body>
</html>

and The jQuery :

$(document).ready(function(){
    //To add a task when the user hits the return key
    $('#task-text').keydown(function(evt){
      if(evt.keyCode == 13)
      {
        add_task(this, evt);
      }
      });
    //To add a task when the user clicks on the submit button
      $("#add-task").click(function(evt){
        add_task(document.getElementByID("task-text"),evt);
        });
    });

function add_task(textBox, evt){
  evt.preventDefault();
  var taskText = textBox.value;
  $("<li>").text(taskText).appendTo("#tasks");
  textBox.value = "";
};

When I add elements By hitting the return key, there’s no problem.
But When I click the Submit Button then firebug shows this error

document.getElementByID is not a function
[Break On This Error] add_task(document.getElementByID("task-text"),evt);
task-list.js (line 11)

I tried to use jQuery instead replacing it with

$("#task-text")

This time the error is :

$("<li>").text(taskText).appendTo is not a function
[Break On This Error] $("<li>").text(taskText).appendTo("#tasks");
task-list.js (line 18
which results in the following error

I’ve been trying to debug this for some time but i just don’t get it. Its probably a really silly mistake that i’ve made. Any help is most appreciated.

Edit :
I’m using jQuery 1.6.1

Cover image for About "getElementById is not a function" in JavaScript

Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a 💯 user experience. ~reza

The error “TypeError: getElementById is not a function” happens for two common reasons (Based on StackOverflow users):

  1. The capitalization of “Id” isn’t correct
  2. Calling getElementById() on an element instead of the document object

Here’s what this error looks like in the browser’s console:

Image description

How to fix the “TypeError: getElementById is not a function” error

Before anything, let’s have a refresher from the MDN Docs:

The getElementById() method returns an Element object representing the element whose id property matches the specified string.

As mentioned earlier, either the capitalization of ID is incorrect, or you’re calling this method on an element other than the document object.

If the capitalization of “Id” isn’t correct: It’s getElementbyId() and not getElementbyID() – Note the capitalized D.

Since we use ID as an abbreviation for identifier or identity document, it might feel natural to write it all in caps. But in the case of getDocumentById(), it has to be Id (with lowercase d):

// ⛔ Incorrect
const element = document.getElementByID('id-string')

// Raises Uncaught TypeError: getElementById is not a function
Here's the correct form:


// ✅ Correct
const element = document.getElementById('id-string')

Enter fullscreen mode

Exit fullscreen mode

If getElementById() is called on an element rather than the document object: Unlike other element locators like querySelector() — that are available on Element objects — The getElementById() function is only available as a method of the document object.

The reason is ID values are supposed to be unique throughout the document, and there is no need for «local» versions of getElementById().

Let’s suppose this is our HTML document:

<!doctype html>
<html>
<head>
    <title>Testing document.getElementbyId()</title>
</head>
<body>
    <section id=container>
        <button id=button></button>
    </section>
</body>
</html>

Enter fullscreen mode

Exit fullscreen mode

To get the button element:

// ✅ Correct form: 
const containerElement = document.getElementById('container')
const buttonElement = document.getElementByID('button')

// ⛔ But this raises the TypeError: getElementById is not a function error
buttonElement = containerElement.getElementByID('button')

Enter fullscreen mode

Exit fullscreen mode

Please note the ID string we pass to the function is also case-sensitive. So if the result of getElementById() is null, you might want to double check the ID string.

Here’s an example:

// ⚠️ returns null since the ID is button not Button
const button = document.getElementById('Button')

// ✅ This is correct
button = document.getElementById('button')

Enter fullscreen mode

Exit fullscreen mode

Alright, I think that does it. If you use the «TypeError: getElementById is not a function» in your Vue or React project, the solution would be the same.

I hope this quick guide helped you fix your problem.

Thanks for reading.


❤️ You might like:

  • How to check if an element exists in JavaScript (with examples)
  • JavaScript isset Equivalent (3 methods)
  • TypeError: map is not a function in JavaScript in JavaScript (Fixed)
  • SyntaxError: Unexpected end of JSON input in JavaScript (Fixed)
  • How to fix «ReferenceError: document is not defined» in JavaScript

TypeError: «x» is not a function

The JavaScript exception «is not a function» occurs when there was an attempt to call a value from a function, but the value is not actually a function.

Message

TypeError: Object doesn't support property or method {x} (Edge)
TypeError: "x" is not a function

Error type

TypeError

What went wrong?

It attempted to call a value from a function, but the value is not actually a function. Some code expects you to provide a function, but that didn’t happen.

Maybe there is a typo in the function name? Maybe the object you are calling the method on does not have this function? For example, JavaScript Objects have no map function, but the JavaScript Array object does.

There are many built-in functions in need of a (callback) function. You will have to provide a function in order to have these methods working properly:

  • When working with Array or TypedArray objects:
    • Array.prototype.every(), Array.prototype.some(), Array.prototype.forEach(), Array.prototype.map(), Array.prototype.filter(), Array.prototype.reduce(), Array.prototype.reduceRight(), Array.prototype.find()
  • When working with Map and Set objects:
    • Map.prototype.forEach() and Set.prototype.forEach()

Examples

A typo in the function name

In this case, which happens way too often, there is a typo in the method name:

let x = document.getElementByID('foo');

The correct function name is getElementById:

let x = document.getElementById('foo');

Function called on the wrong object

For certain methods, you have to provide a (callback) function and it will work on specific objects only. In this example, Array.prototype.map() is used, which will work with Array objects only.

let obj = {a: 13, b: 37, c: 42};

obj.map(function(num) {
  return num * 2;
});


Use an array instead:

let numbers = [1, 4, 9];

numbers.map(function(num) {
  return num * 2;
});


Function shares a name with a pre-existing property

Sometimes when making a class, you may have a property and a function with the same name. Upon calling the function, the compiler thinks that the function ceases to exist.

var Dog = function () {
 this.age = 11;
 this.color = "black";
 this.name = "Ralph";
 return this;
}

Dog.prototype.name = function(name) {
 this.name = name;
 return this;
}

var myNewDog = new Dog();
myNewDog.name("Cassidy"); 

Use a different property name instead:

var Dog = function () {
 this.age = 11;
 this.color = "black";
 this.dogName = "Ralph"; 
 return this;
}

Dog.prototype.name = function(name) {
 this.dogName = name;
 return this;
}

var myNewDog = new Dog();
myNewDog.name("Cassidy"); 

Using brackets for multiplication

In math, you can write 2 × (3 + 5) as 2*(3 + 5) or just 2(3 + 5).

Using the latter will throw an error:

const sixteen = 2(3 + 5);
alert('2 x (3 + 5) is ' + String(sixteen));

You can correct the code by adding a * operator:

const sixteen = 2 * (3 + 5);
alert('2 x (3 + 5) is ' + String(sixteen));

Import the exported module correctly

Ensure you are importing the module correctly.

An example helpers library (helpers.js)

let helpers = function () { };

helpers.groupBy = function (objectArray, property) {
  return objectArray.reduce(function (acc, obj) {
    var key = obj[property];
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(obj);
    return acc;
  },
{});
}

export default helpers;

The correct import usage (App.js):

import helpers from './helpers'

See also

  • Functions

The Javascript error TypeError: "x" is not a function occurs when there is an attempt to call a function on a value or object, which is not actually a function.

Error message:

TypeError: "x" is not a function

Error Type:

TypeError

What Causes TypeError: «x» is not a function

A TypeError: "x" is not a function in Javascript generally occurs in one of the following scenarios:

  • A typographical error in a function call.
  • Missing script library.
  • When a function is called on a property that is not actually a function.
  • A TypeError: "x" is not a function occurs when a function is called on an object that does not contain the called function.
  • When calling a built-in function that expects a callback function argument, which does not exist.
  • When the called function is within a scope that is not accessible

TypeError: «x» is not a function Examples

1. Typo

A typical scenario for the TypeError: "x" is not a function to occur is when there is a typo in the called function name:

var elem = document.getElementByID('ID');

Running the above code leads to the following Javascript error:

TypeError: document.getElementByID is not a function

The correct function name is getElementById():

var elem = document.getElementById('ID');

2. Object Does Not Contain Function

Another common cause for the TypeError: "x" is not a function is when a function is called an object that does not actually contain the function:

var foo = {
   bar: function() {
      console.log("bar called");
   }
};
foo.baz();

In the above example, the foo object contains a function bar(). However, the above code attempts to call the function baz(), which foo does not contain. Running the above code leads to the following Uncaught TypeError: "x" is not a function:

Uncaught TypeError: foo.baz is not a function

If the Javascript code is modified to call the correct function bar():

var foo = {
   bar: function() {
      console.log("bar called");
   }
};    
foo.bar();

The correct output is produced:

bar called

How to Fix Javascript TypeError: «x» is not a function

The TypeError: "x" is not a function can be fixed using the following suggestions:

  • Paying attention to detail in code and minimizing typos.
  • Importing the correct and relevant script libraries used in code.
  • Making sure the called property of an object is actually a function.
  • Making sure objects contain the called function to avoid TypeError: "x" is not a function.
  • Making sure functions passed in as callbacks do exist.
  • Making sure called functions are within the correct and accessible scope.

Track, Analyze and Manage Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Javascript errors easier than ever. Sign Up Today!

Понравилась статья? Поделить с друзьями:
  • Ошибка dsc бмв е65
  • Ошибка docker build requires exactly 1 argument
  • Ошибка dsc бмв е39
  • Ошибка doc информатика 6 класс скачать
  • Ошибка dsc off mazda 6