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

后端 未结 1 517
耶瑟儿~
耶瑟儿~ 2020-12-07 02:56

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

Th

相关标签:
1条回答
  • 2020-12-07 03:42

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

    0 讨论(0)
提交回复
热议问题