Here is the HTML code:
<p onclick='javascript:func(this);'>Bla bla bla</p>
and here is the script (it is written in the head of the document):
function func(e) {
var t = e.text();
console.log(t);
}
It doesn't work and I don't understand why. The error message is:
"Object # has no method 'text'".
Here is the HTML code:
<p onclick='javascript:func(this);'>Bla bla bla</p>
and here is the script (it is written in the head of the document):
function func(e) {
var t = e.text();
console.log(t);
}
It doesn't work and I don't understand why. The error message is:
Share Improve this question edited Jul 17, 2022 at 22:11 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jul 5, 2013 at 6:44 enjakuenjaku 3464 silver badges18 bronze badges 1"Object # has no method 'text'".
- I don't see any jQuery. – Felix Kling Commented Jul 5, 2013 at 6:59
6 Answers
Reset to default 5Wrap it in the jQuery wrapper. .text()
is a jQuery method, and your element e
is a plain Javascript DOM element, so you need the jQuery wrapper.
var t = $(e).text();
Side note: unobtrusive event handler assignments are preferred to inline handlers. For example:
$(document).ready(function(){
$('p').click(function(){
var t = $(this).text();
console.log(t);
});
});
The above uses jQuery to assign the click handler (instead of inline Javascript) and so because of that, the element can be accessed in this
for the plain Javascript object, or $(this)
for the jQuery object.
Fiddle
This is plain javascript and will do what you ask for.
function func(e) {
var t = e.innerHTML;
console.log(t);
}
Use innerText
if you do not use jquery.
function func(e) {
var t = e.innerText;
console.log(t);
}
Right way is:
HTML:
<p onclick='func(this);'>Bla bla bla</p>
instead of
<p onclick='javascript:func(this);'>Bla bla bla</p>
Javascript:
function func(e) {
var t = e.innerHTML;
console.log(t);
}
Jquery is designed to be unobtrusive. If your adding onclick attributes everywhere your doing it wrong.
Instead you should be adding event listeners
<p>Blah Blah Blah</p>
Jquery/Script
$(document).ready(function(){
$('p').on('click', function(){
console.log($(this).text());
});
});
Try using innerHTML
:
function func(e) {
var t= e.innerHTML;
console.log(t);
}