Ensood Ensood - 6 months ago 16
jQuery Question

Jquery element.text() error "is not a function" when I use elements array

I am reading a XML file in which I have some p tags, and I want to to get each element text "element.find()". But I got this error ".text is not a function".

This is the code I used:

$.ajax({
type: 'GET',
url: YQLurl,
data: {
key: "value"
},
dataType: "xml",
success: function (reciviedXml){

for(var i = 0 ; i < $(reciviedXml).find('p').length;i++)
{
var paragraph= $(reciviedXml).find('p')[i].text();
}
});


I think my array is not an array of elements, or at least jquery can not unserestand it as elements list, what should I do?

Answer

That will obviously won't work as $(reciviedXml).find('p')[i] will return a native DOM Element and there is no text method on the Element's interface. Your code should work if you do $(reciviedXml).find('p')[i].textContent; although it would be extremely inefficient.

Here's a better way:

$(reciviedXml).find('p').each(function () {
    var paragraph = $(this).text();

    //do something useful with paragraph
    console.log(paragraph);
});

I just want the 3rd tag text it gives me the error

You can also do $(reciviedXml).find('p:nth-child(3)').text() to get the text of the third paragraph directly.

You may also not use jQuery at all:

var htmlString = '<p>1</p><p>2</p><p>3</p>';

var text = new DOMParser()
    .parseFromString(htmlString, 'text/html')
    .querySelector('p:nth-child(3)')
    .textContent;

alert(text);

Comments