“$.trim is not a function”: Reading a Copied jQuery Snippet Line by Line

jQuery loaded fine — it just isn’t the jQuery your snippet was written for. Six helpers vanished in 4.0.0 and four survived; here’s how to tell which is which.

7 min read

Argued into existence in the Writing Room7 messages · 1 mind changed“$.trim is not a function”: Reading a Copied jQuery Snippet Line by Line

TypeError: $.trim is not a function

That's the whole message. No missing script, no 404, no red network row. Your page loaded jQuery (a JavaScript library of ready-made helper functions), called it, and jQuery said it doesn't know that one.

If you searched the error and found a pile of answers about "$ is not defined," those are correct and not yours. "$ is not defined" means jQuery never loaded: wrong order, wrong path, blocked script. Add the tag, move it above your code, done. "$.trim is not a function" means the opposite. jQuery is there. It's just not the jQuery your snippet was written for.

Here is the test this whole piece is really about, up front: for each line in that snippet, ask whether the browser now does the same job on its own. The helpers jQuery 4 removed are exactly the ones where the answer is yes — and a line the platform can already do is the line any library update is free to delete out from under you. By the end you'll be able to find which jQuery your page has, read the error, and fix old lines by asking whether the browser now does the job itself.

Find out which jQuery you have

Open the Console (right-click the page, choose Inspect, then the Console tab) and type this:

$.fn.jquery

I ran the same checks against two real copies from npm, the registry JavaScript packages are downloaded from. One prints '3.7.1'. The other prints '4.0.0' (its file header is dated 2026-01-18). Version 4 is the first new major number after the 3.x line (the major is the first digit — bumping it is where a library is allowed to remove things), and it can reach you without you choosing it: a theme, a plugin (an add-on script), or a CMS (content management system) update can swap the file under a snippet you pasted years ago. Pinning, meaning locking your page to the old version, is a legitimate bandage.

Probe which helpers are gone

Here is a probe you can paste into the Console of any page that has jQuery on it. It asks, for each helper — one of those '$.'-prefixed utility functions — whether it still exists as a function:

console.log($.fn.jquery);
['trim','isArray','parseJSON','isFunction','isNumeric','now','proxy','each','ajax','Deferred']
  .forEach(n => console.log(n.padEnd(10), typeof $[n] === 'function' ? 'ok' : 'GONE'));

The probe itself is the same text on both versions. I ran each in Node 22 (a program that runs JavaScript outside the browser) with jsdom (which fakes a web page for it). In a browser you skip all that: the page already has jQuery, you just paste. The output:

3.7.1                       4.0.0
trim       ok               trim       GONE
isArray    ok               isArray    GONE
parseJSON  ok               parseJSON  GONE
isFunction ok               isFunction GONE
isNumeric  ok               isNumeric  GONE
now        ok               now        GONE
proxy      ok               proxy      ok
each       ok               each       ok
ajax       ok               ajax       ok
Deferred   ok               Deferred   ok

(I put the two runs side by side; the script prints them one after the other.)

One caveat before you read a GONE as proof you're on version 4: jQuery also ships a 'slim' build — a smaller file that leaves out ajax (requests to a server) and the Deferred and animation code — so a GONE next to 'ajax' can mean someone loaded the slim file, not that the major number changed. The version line you printed first settles which it is. jQuery documents every one of these removals in its official 4.0 Upgrade Guide on jquery.com, worth reading before you pin the old file back.

Six gone, four fine. And the gone ones are not the oldest ones. '$.ajax' is about as 2006 as jQuery gets, and it works untouched on 4.0.0.

The old lines and their native replacements

Here is what I typed for each line that old snippets actually contain. "Works" means it gave the same answer on 3.7.1 and 4.0.0.

  • '$(document).ready(fn)': works on both. It fired on both. So did the short form '$(fn)'.
  • '$("#list .item")': works. Found 2 elements on both.
  • '.on("click", fn)': works. The older shorthand '.click(fn)' also still works on 4.0.0, in the form that attaches a handler and in the form that triggers one.
  • '$.ajax', '$.get', '$.getJSON': work on the standard build. More on the slim build in a moment.
  • '$.each', '$.extend', '$.inArray': work.
  • '$.trim(" hi ")': throws on 4.0.0. Write '" hi ".trim()'. It's a method on the string itself.
  • '$.isArray(x)': throws. Write 'Array.isArray(x)'.
  • '$.parseJSON(s)': throws. Write 'JSON.parse(s)'.
  • '$.isFunction(x)': throws. Write 'typeof x === "function"'.
  • '$.now()': throws. Write 'Date.now()'.
  • '$.isNumeric(x)': throws. See below.
  • '$.Deferred()': works on the standard build. Throws on the slim build.

One trap in that list. It's tempting to translate '$.trim(s)' as 'String.trim(s)'. I typed it: 'String.trim' is undefined. 'trim' lives on a string value (a piece of text), not on the String constructor.

Where it goes wrong: the error blames another line

Most copied snippets put their code inside '$(document).ready'. So here is what that looks like. I took a small old snippet and ran it on 4.0.0:

$(document).ready(function () {
  const name = $.trim($('#name').val());
  if ($.isArray([name])) $('#out').text('Hello, ' + name);
});

The paragraph stayed empty. The output began with the line 'jQuery.Deferred exception TypeError: $.trim is not a function', then the plain 'TypeError: $.trim is not a function' with a stack trace (the list of calls that led to the error) that runs through jQuery's own file. If you only skim, you'll blame jQuery's Deferred. Don't. The first frame of the stack is the one in your file, and it names the real culprit. (I ran this in Node with jsdom, so your browser will format the lines its own way.)

The fixed version, same page, same input:

$(function () {
  const name = $('#name').val().trim();
  if (Array.isArray([name])) $('#out').text('Hello, ' + name);
});

It printed 'Hello, Ada', trimmed. Both '$(document).ready' and the '$(function)' shorthand ran on 4.0.0; I only changed the two dead helpers.

Three replacements that need care

Rewriting '$.isNumeric' takes thought, because "numeric" was a decision jQuery made for you. The old check was roughly 'not NaN (not-a-number) after parseFloat, and finite'. I wrote that expression, ran it on eight inputs, and compared it with 3.7.1's own '$.isNumeric' on the same inputs:

const isNumeric = x => !isNaN(parseFloat(x)) && isFinite(x);
['5', '', ' ', '1e3', 'abc', 5, null, '0x10'].map(isNumeric);
// true, false, false, true, false, true, false, true

Same eight answers from both. Note what it says: '"0x10"' counts as numeric and '"1e3"' too. If your form accepts prices, you may not want that, which is exactly why a silent helper was a poor place to hide the decision.

The '$.ajax' translation is 'fetch', the browser's built-in way to request data from a server, and it's one line longer than you'd like:

const res = await fetch('/user');
const user = await res.json();      // replaces $.parseJSON on the body
console.log(user.name.trim());      // printed: Ada

I ran that against a tiny local server returning '{"name":" Ada "}'. Sure, but — fetch doesn't throw on a 404 the way '$.ajax' calls your error callback. I checked: a 404 came back with 'res.ok' false and no exception. That difference is yours to handle, and it's worth knowing before you swap.

'$.Deferred' — jQuery's own older way of building a promise, an object standing for a result that arrives later — is the surprise. I ran the probe on the slim builds too. On 3.7.1 slim, '$.Deferred' still worked and only '$.ajax' and the effects were gone. On 4.0.0 slim, '$.Deferred' and '$.when' are undefined as well. If your snippet uses '$.Deferred().resolve()' and someone swapped in the slim file, the error blames your line, but the file changed underneath it. For most snippets a native promise does the job:

const done = new Promise(resolve => setTimeout(() => resolve('done'), 10));
console.log(await done);   // printed: done

The concept: the browser already does it

Back to that 6-and-4 split. From these twelve: the helpers that died are one-line type checks and string tidiers, things where the browser's own version now exists and does the same job. The ones that lived either do something the browser still makes clumsy in one call, like selecting a set and attaching events to all of it, or sit at the core of the library.

That gives you a test you can carry into any copied snippet, jQuery or not. For each line ask: does the platform now say this in a native method? If yes, that line is the one a library update can delete, and you should rewrite it before it is deleted for you. If no, it's the load-bearing part, and the library will defend it.

Also look at where the Console points. If the file in the error is a plugin or a theme script rather than your own, the line isn't yours to patch. The move is to update that plugin or theme to a version built for jQuery 4, or pin jQuery back to the 3.x line until it ships one. I haven't audited any specific plugin, so check the file name in the message before you edit anything.

Live demoSimulation: the same snippet on jQuery 3.7.1 and 4.0.0
Show the code
<style>
  fieldset { border: 1px solid #ccc; border-radius: 8px; margin: 0 0 10px; padding: 6px 10px 8px; }
  legend { font-weight: 600; padding: 0 4px; }
  label.opt { display: inline-flex; align-items: center; gap: 6px; min-height: 36px; margin-right: 14px; }
  pre { margin: 0 0 10px; white-space: pre-wrap; word-break: break-word; font-size: 15px; background: #f6f6f6; padding: 8px; border-radius: 6px; }
  #con { background: #1d1d1f; color: #f2f2f2; }
  button { min-height: 40px; padding: 0 18px; font: inherit; border: 1px solid #888; border-radius: 8px; background: #f2f2f2; cursor: pointer; }
  .para { border: 1px dashed #aaa; border-radius: 6px; padding: 8px; min-height: 2.6em; }
</style>
<p>The name field holds "&nbsp;&nbsp;Ada&nbsp;&nbsp;". Pick a jQuery version and a snippet, then press Run.</p>
<fieldset><legend>jQuery on the page</legend>
  <label class="opt"><input type="radio" name="ver" id="v3" value="3.7.1" checked> 3.7.1</label>
  <label class="opt"><input type="radio" name="ver" id="v4" value="4.0.0"> 4.0.0</label>
</fieldset>
<fieldset><legend>Your snippet</legend>
  <label class="opt"><input type="radio" name="snip" id="old" value="old" checked> Old helpers</label>
  <label class="opt"><input type="radio" name="snip" id="native" value="native"> Native replacements</label>
</fieldset>
<pre id="code"></pre>
<button id="run">Run</button>
<p>The paragraph #out:</p>
<div class="para" id="out"></div>
<p>Console:</p>
<pre id="con">(nothing yet)</pre>
<script>
  // A stand-in for jQuery, just big enough for this snippet. 3.7.1 still has the
  // helpers; 4.0.0 removed them, so $.trim and $.isArray are simply not there.
  function fakeJQuery(version) {
    const $ = (sel) => ({
      val: () => '  Ada  ',
      text: (t) => { document.getElementById('out').textContent = t; },
    });
    $.fn = { jquery: version };
    if (version === '3.7.1') { $.trim = (s) => s.trim(); $.isArray = Array.isArray; }
    return $;
  }
  const SNIPPETS = {
    old: "const name = $.trim($('#name').val());\nif ($.isArray([name])) $('#out').text('Hello, ' + name);",
    native: "const name = $('#name').val().trim();\nif (Array.isArray([name])) $('#out').text('Hello, ' + name);",
  };
  const picked = (n) => document.querySelector('input[name=' + n + ']:checked').value;
  function showCode() { document.getElementById('code').textContent = SNIPPETS[picked('snip')]; }
  document.querySelectorAll('input[name=snip]').forEach((r) => r.addEventListener('change', showCode));
  document.getElementById('run').onclick = () => {
    const version = picked('ver');
    const con = document.getElementById('con');
    document.getElementById('out').textContent = '';
    const $ = fakeJQuery(version);
    try {
      new Function('$', SNIPPETS[picked('snip')])($); // really runs the snippet text above
      con.textContent = '$.fn.jquery → ' + $.fn.jquery + '\n(no errors)';
    } catch (e) {
      con.textContent = '$.fn.jquery → ' + $.fn.jquery + '\n' + e.name + ': ' + e.message;
    }
  };
  showCode();
</script>

Recap

  • "$.trim is not a function" means jQuery loaded, but not the version your snippet expects.
  • Print '$.fn.jquery' to see the version, and run the probe to see which helpers are gone.
  • The removed helpers are ones the browser now does itself, such as '.trim()', 'Array.isArray' and 'JSON.parse'.
  • The first stack frame in your own file names the real culprit, and a plugin's line is the plugin's to update.

Next, run that question over a copied snippet of your own: for each line, does the platform now do this natively? Rewrite those lines before an update deletes them for you.

“$.trim is not a function”: Reading a Copied jQuery Snippet Line by Line | Vibecodes