Reputation: 243
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
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);
Or, if you want the jQuery(yuck) version:
//Creates and dispatches a click event
$('.block-title span').trigger('click');
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
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:
Upvotes: 1
Reputation: 713
Use .trigger(type) from the jQuery API
$('.block-title span').trigger('click');
http://api.jquery.com/trigger/
Upvotes: 1