ashen25
ashen25

Reputation: 25

Get text inside an element using javascript

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

Upvotes: 0

Views: 1091

Answers (4)

zhack
zhack

Reputation: 149

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

Upvotes: 0

connexo
connexo

Reputation: 56720

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

Upvotes: 3

Vencovsky
Vencovsky

Reputation: 31565

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

Upvotes: 0

Andrew MacNaughton
Andrew MacNaughton

Reputation: 813

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

Upvotes: 0

Related Questions