最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How to click on a <span> using javascript. <span> has no class or id - Stack Overflow

programmeradmin4浏览0评论

I want to click on a <span> on page element load but my span has no class or ID.
The span is

<div class="block-title">
<strong><span>Refine By</span></strong>
</div>

I want something like

 $('.block-title > span').click(); 

But this returns error

TypeError: $(...) is null

I want to click on a <span> on page element load but my span has no class or ID.
The span is

<div class="block-title">
<strong><span>Refine By</span></strong>
</div>

I want something like

 $('.block-title > span').click(); 

But this returns error

TypeError: $(...) is null

Share Improve this question edited Dec 7, 2015 at 16:20 Mr Lister 46.6k15 gold badges113 silver badges155 bronze badges asked Dec 2, 2015 at 15:49 Sheikh SiddiqueeSheikh Siddiquee 2433 gold badges4 silver badges14 bronze badges 8
  • You want to attach a click event to it? – AtheistP3ace Commented Dec 2, 2015 at 15:51
  • $('.block-title > span').click(function() { }); – Nenad Vracar Commented Dec 2, 2015 at 15:51
  • I want some thing like this $('.block-title > span').click(); But this returns error TypeError: $(...) is null – Sheikh Siddiquee Commented Dec 2, 2015 at 15:52
  • You mean $('.block-title span').click(); You need to adjust your selector first – Erwin O. Commented Dec 2, 2015 at 15:58
  • @ Erwin this gives error in console TypeError: $(...) is null – Sheikh Siddiquee Commented Dec 2, 2015 at 16:01
 |  Show 3 more ments

3 Answers 3

Reset to default 9

If you want to trigger a click on the element, you can do it like this:

var span= document.querySelector(".block-title span");
var click= new Event('click');
span.dispatchEvent(click);

Complete Vanilla JS Demo

Or, if you want the jQuery(yuck) version:

//Creates and dispatches a click event
$('.block-title span').trigger('click');

Complete jQuery Version


Older answer

Using pure javascript, you can set the onclick of an element to a function:

document.querySelector(".block-title span").onclick = fn;
// or like document.querySelector(".block-title span").onclick = function(){};

Or, if you want to use an event listener:

var span = document.querySelector(".block-title span");
span.attachEvent('onclick', fn);
span.addEventListener('click', fn, false);

Or, if you want to use jQuery(yuck):

$('.block-title span').click(function() { });

Use .trigger(type) from the jQuery API

$('.block-title span').trigger('click');

http://api.jquery./trigger/

If you get the following error then it means there is some other issue with your javascript:

TypeError: $(...) is null

I would suggest doing some research. I copied that into Google and got:

  1. TypeError: $(...) is null error in firebug but code works on jsFiddle
  2. "TypeError: $(...) is null" What's Going On?
  3. Class exists but jquery errors: TypeError $(...) is null
发布评论

评论列表(0)

  1. 暂无评论