iabudiab / HTMLKit

An Objective-C framework for your everyday HTML needs.
MIT License
239 stars 27 forks source link

:gt(0) can't get elements #25

Closed samhuangszu closed 6 years ago

samhuangszu commented 6 years ago

When I write the code as follow, it works:

CSSSelector * gtSelector(NSInteger index)
{
    NSString *name = [NSString stringWithFormat:@":gt(%ld)", (long)index];
    return namedBlockSelector(name, ^BOOL(HTMLElement * _Nonnull element) {
        NSUInteger elementIndex = [element.parentElement indexOfChildNode:element];

        if (index > 0) {
            return elementIndex > index;
        } else {
            return (elementIndex > index && elementIndex < element.parentElement.childNodesCount);
        }
    });
}
iabudiab commented 6 years ago

@samhuangszu Hey there, what exactly is not working? Could you give me an example document and the desired elements that you want to select?

The semantics of the gt(n) selector are defined the same as its jQuery counterpart, take a look here in the docs

Here is also a working example:

NSString *html = @"<table>\
  <tr><td>TD #0</td><td>TD #1</td><td>TD #2</td><td>TD #3</td><td>TD #4</td></tr>\
  </table>";

HTMLDocument *doc = [HTMLDocument documentWithString:html];
NSArray<HTMLElement *> *elements = [doc elementsMatchingSelector:gtSelector(1)];

// You can also use the string version of the selector:
// NSArray<HTMLElement *> *elements = [doc querySelectorAll:@":gt(1)"];

for (HTMLElement *element in elements) {
  NSLog(@"%@\n", element.textContent);
}

// Output
// TD #2
// TD #3
// TD #4

Notice that gt(n) is zero-based, whereas :nth-child(n) is 1-based.

samhuangszu commented 6 years ago

http://m.zhuaji.org/wap/all/21258 this page,and the css selector is #chapterlist p:gt(0) a array = [doc querySelectorAll:@"#chapterlist p:gt(0) a"] array.count ==0

iabudiab commented 6 years ago

@samhuangszu Hey there, this is indeed a bug. Fix is on the way.

The problem was in the positive index check. Zero was not considered positive, which lead to the else-case in the selector.

This is also the case with lt(0) and eq(0) selectors.

iabudiab commented 6 years ago

New release with fix will be up tomorrow.