Sheikh Siddiquee
Sheikh Siddiquee

Reputation: 243

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

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

Upvotes: 2

Views: 24776

Answers (3)

Jacob G
Jacob G

Reputation: 14172

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() { });

Upvotes: 9

Vince
Vince

Reputation: 1851

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

Upvotes: 1

Kerstomaat
Kerstomaat

Reputation: 713

Use .trigger(type) from the jQuery API

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

http://api.jquery.com/trigger/

Upvotes: 1

Related Questions