Reputation: 15836
I have a span with a text inside it like :
<span class="characters-count">(160 Characters Left)</span>
given the span a class in this case .characters-count
, when i tried class selector using jQuery to get the text inside span :
$(".characters-count")[0].text();
it returns undefined !
However this selector works well :
$("span.characters-count").text();
anyone can explain what is happening ?
Upvotes: 2
Views: 13752
Reputation: 6031
you need to use innerText instead of text() when you use $(".characters-count")[0] check DEMO
$(".characters-count")[0].innerText
Upvotes: 1
Reputation: 3015
console.log($(".characters-count:first").text())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="characters-count">(160 Characters Left)</span>
try something like this:
$(".characters-count:first").text()
Check here, why it was not working for you.
//This will return dom element, so it doesn't have `text()` method, that's why it was throwing error for you.
console.log($(".characters-count:first")[0]);
// This will return object of an element, you can use jQuery selectors to get first element from collection and set text to it
console.log($("span.characters-count"));
console.log($("span.characters-count:first").text
);
Upvotes: 1
Reputation: 77482
$("span.characters-count").text();
In our case you work with jQuery Object that has text
method
$(".characters-count")[0].text();
In this case you work with actual DOM element (like document.getElementByClassName('characters-count')[0]
) that does not have text
method
Upvotes: 4