How can I pass the value, or text content of a span to a jQuery function, while executing that function onClick?
I tried a few things like the following, but with no luck:
<span onClick="sceSelect()">Next</span>
I'm trying to pass the value "Next", but haven't been able to. I cannot use getElementByID, because the content inside the span is generated dynamically, and being places into the html from an array that will have multiple different values being placed into the html as sepparate s, but I need each one to activate a function and pass its value to it onClick.
If you must use in-line event-handling:
<span onclick="sceSelect((this.textContent || this.innerText))">Next</span>
Incidentally you don't need to camel-case (onClick
) the onclick
attribute.
This assumes, of course, that your function expects a parameter to be passed, for example:
function sceSelect(elementText){
}
You could, of course, also pass the node itself in the function-call (which would make more sense, frankly) (and as bfaveretto notes, elsewhere).
I'm not, however, convinced there's any reason to use inline event-handling when it comes to jQuery, using:
$('span').click(function(){
sceSelect(this);
// or:
sceSelect($(this));
// or:
sceSelect($(this).text());
});
makes far more sense to me (though your use-case is probably quite different than I imagine it might (or should) be).
Incidentally, one way to avoid inline event-handling, if all you're concerned with is avoiding getElementById()
, is to use:
function sceSelect() {
console.log(this.textContent || this.innerText);
}
var spans = document.getElementsByTagName('span');
for (var i = 0, len = spans.length; i < len; i++) {
spans[i].onclick = sceSelect;
}
JS Fiddle demo.
In the scope of the function sceSelect()
the this
object/node is the span
element on which you (or the user) clicked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With