4

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'".

1
  • I don't see any jQuery. Commented Jul 5, 2013 at 6:59

6 Answers 6

5

Wrap 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.

Sign up to request clarification or add additional context in comments.

Comments

0

Fiddle

This is plain javascript and will do what you ask for.

function func(e) {
  var t = e.innerHTML;
  console.log(t);
}

Comments

0

Use innerText if you do not use jquery.

function func(e) {
  var t = e.innerText;
  console.log(t);
}

Comments

0

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

Comments

0

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

Comments

0

Try using innerHTML:

function func(e) {
    var t= e.innerHTML;
    console.log(t);
}

1 Comment

Sorry if you were just about to edit it yourself, but it was in the LQP review list ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.