Bajro Bajro - 4 months ago 9
Javascript Question

JQuery .text() for element in array

I want to first find all elements in the html document which have the same class name and are an anchor tag and get the text out of it.

HTML:

<div class="links" id="one">
<span class="info">useless links</span>
<a class="anchorTag" href="www.sample.com">Click me!</a>
<a class="anchorTag" href="www.sample.com">Click me again!</a>
<a class="anchorTag" href="www.sample.com">Click me once again!</a>
<a class="anchorTag" href="www.sample.com">Click me one last time!</a>
</div>
<div class="links" id="two">
<span class="info">secret links</span>
<a class="anchorTag" href="www.sample.com">Click me!</a>
<a class="anchorTag" href="www.sample.com">Click me again!</a>
<a class="anchorTag" href="www.sample.com">Click me once again!</a>
<a class="anchorTag" href="www.sample.com">Click me one last time!</a>
</div>


Code:

$('.links').each(function(){
if($(this).find("span.info").text() == "secret link"){
var allLinks = $(this).find("a.anchorTag");
console.log(allLinks[0].text());
}
});


Error:


console.log(allLinks[0].text()) is not a function


If I print the length of the var allLinks, it returns the correct size, but it won't print the text of the specific element in the array when accessing it with the index? Why is that so?

Answer

allLinks is not an actual array, but rather a set of DOM elements. That said, normal array operators won't work on it. If you want to print the text of the first element in the set, rather than this:

console.log(allLinks[0].text());

You should use the jquery .first() method like this:

console.log(allLinks.first().text());
Comments