0

I am trying to get a text content inside a div using jquery. But it returns 'undefined'. Please someone tell me what i'm doing wrong here. this is my code.

<a><div class="exc_text">Some text here</div></a>


$(document).on('click','.exc_text',function(){
    var text = $(this).textContent;
    console.log(text);
});
0

4 Answers 4

3

textContent is a property on native elements, not on jQuery objects. $(this) wraps this (which is a native DOM element) in a jQuery object.

Either stick to the native DOM api (and go with textContent) - which is what I'd recommend:

document.addEventListener('click', (e) => {
  if (e.target.classList.contains('exc_text') {
    console.log(e.target.textContent);
  }
})

Or stick with jQuery if you have to (and use .text()):

$(document).on('click', '.exc_text', function(){
    var text = $(this).text();
    console.log(text);
});
Sign up to request clarification or add additional context in comments.

Comments

0

You're reselecting the element with jQuery which you don't need to do. Try this

 $(document).on('click','.exc_text',function(){
    var text = this.textContent;
    console.log(text);
});

The easiest way to solve this is to look in dev tools. All i did was break on the second link, and hovered over this, which showed me that it was an element so no need to reselect it...

Comments

0

You should use .text() instead of .textContent

<a><div class="exc_text">Some text here</div></a>

$(document).on('click','.exc_text',function(){
    var text = $(this).text();
    console.log(text);
});

Comments

0

Just simply use .text()

<a><div class="exc_text">Some text here</div></a>


$(document).on('click','.exc_text', function(){
    var text = $(this).text();
    console.log(text);
});

Comments

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.