简体   繁体   中英

Jquery/Json - How can I get the last <P> in this JSON object?

The usual .last or :last jquery selectors are not doing it for me. I have an object content.object that has HTML in it like

<P>
item 1
</P>
<P>
item 2
</P>
<P>
item 3
</P>

I have tried

var lastItem = $(content.object).find('p:last');

and

var lastItem = $(content.object).find('p').last();

But these aren't doing the trick and I keep getting errors. How can I get the text in the last

?

The find method wont work because you are already inside the same depth as the p tags

If your JSON object looks like this

var content = {
    object: '<P>item 1</P><P>item 2</P><P>item 3</P>'
};

You can access the last p like so:

var lastItem = $( content.object ).last();

You need to use filter

var lastItem = $(content.object).filter('p:last');

.filter : Reduce the set of matched elements to those that match the selector or pass the function's test. .find : Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

Demo: Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM