$(…).each is not a function

我的梦境 提交于 2019-12-02 20:32:17

1) Paste:

var script = document.createElement('script');
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(script);

on your console (includes jQuery)

2) Wait 1 sec and paste:

var h2Arr = [];
$('h2').each( function() {
    h2Arr.push($(this).html());
});

Now, all contents of h2 tags of that page should be stored into h2Arr

if you write code like without $() for example

var1.each(function(){}) //its wrong//each function is not defined error

$(var1).each(function(){}) //its right

Note: For Chrome, do not expect $ is always jQuery.

You can put $ into console to check if it returns default ƒ $(selector, [startNode]) { [Command Line API] }, if yes means $ is not defined for jQuery.

Luckily that we have below ways to try:

  1. Solve the conflict of using $, let it be jQuery without any ambiguity

Firstly, you can put this code snippet

var jq = document.createElement('script');
jq.src = "https://code.jquery.com/jquery-3.3.1.min.js";  /* Include any online jquery library you need */
document.getElementsByTagName('head')[0].appendChild(jq);

into the Console, then put $.noConflict into console, if it not returns undefined, but returns ƒ (t){return e.$===w&&(e.$=Kt),t&&e.jQuery===w&&(e.jQuery=Jt),w}, it means $ is not defined for JQuery now.

Next you can continue to input your regional code, then you will find it works well now.

Refer: https://blog.wplauncher.com/run-jquery-in-chrome-console/


  1. Using .js file instead in Chrome, then debug the JavaScript file.

Refer: Chrome DevTools Snippets

  1. Besides, for some specific version of Chrome, there is a option in UI to set the page context (probably removed this function in latest version!)

.

You have to use .html() instead of .innerHTML:

$.each($('h2'), function(index, value){
   alert($(value).html());
});

Here a working fiddle.

The most common cause of this error is because JQuery is not included in your website, that's why it shows this error. You have to include JQuery in your website or rewrite your code in vanilla js.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!