MillyMonster
MillyMonster

Reputation: 556

How to include a script tag only if an element exists?

This seems like something that should be straightforward but I'm a newbie with Javascript, so please be patient.

I want to include a script file but only if an element exists on the page. I've tried:

var element = $('.customelement');

if(element.length() > 0) {
  $('head').append('<script language="javascript" src="custom.js"></script>');
}

But this doesn't work and returns the error:

Uncaught TypeError: Property 'length' of object [object Object] is not a function

I have found many posts which say this should work so I'm a little stumped. I was also wondering if there is a better way to do this?

Upvotes: 2

Views: 3280

Answers (3)

dsgriffin
dsgriffin

Reputation: 68596

By length(), I believe you meant length (It's a Javascript property, not a jQuery function):

if(element.length > 0) {
  $('head').append('<script language="javascript" src="custom.js"></script>');
}

Upvotes: 7

Niko
Niko

Reputation: 26730

As the error message states, length is a property but not a function:

if (element.length > 0) {

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

Exactly what the error says. length is a property, not a function. Remove the ().

Upvotes: 0

Related Questions