javascript - How to include a script tag only if an element exists? - Stack Overflow

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

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?

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?

Share Improve this question edited Apr 12, 2013 at 12:23 dsgriffin 68.6k17 gold badges140 silver badges138 bronze badges asked Apr 12, 2013 at 11:57 MillyMonsterMillyMonster 5564 silver badges21 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

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>');
}

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

if (element.length > 0) {

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742389087a4434652.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信