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
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 8TypeError: $(...) is null
- 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
3 Answers
Reset to default 9If 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:
- TypeError: $(...) is null error in firebug but code works on jsFiddle
- "TypeError: $(...) is null" What's Going On?
- Class exists but jquery errors: TypeError $(...) is null