Deal with the case where the first element does not have the

requested attribute: return Nothing rather than undefined.
This commit is contained in:
Gareth Daniel Smith 2018-07-29 14:55:58 +01:00
parent 4145c4634c
commit ff5d1c3b22
3 changed files with 13 additions and 2 deletions

View File

@ -2,7 +2,13 @@ const cheerio = require('cheerio')
// Attributes // Attributes
exports.attrImpl = function(nothing, just, name, cheerioInst) { exports.attrImpl = function(nothing, just, name, cheerioInst) {
return cheerioInst.length ? just(cheerioInst.attr(name)) : nothing;
if (cheerioInst.length > 0) {
const value = cheerioInst.attr(name);
return value != null ? just(value) : nothing;
}
return nothing;
} }
exports.hasClassImpl = function(className, cheerioInst) { exports.hasClassImpl = function(className, cheerioInst) {

View File

@ -10,7 +10,8 @@ foreign import attrImpl :: forall a.
Fn4 (Maybe a) (a -> Maybe a) String Cheerio (Maybe String) Fn4 (Maybe a) (a -> Maybe a) String Cheerio (Maybe String)
-- | Gets an attribute value from the first selected element, returning -- | Gets an attribute value from the first selected element, returning
-- | Nothing when there are no selected elements. -- | Nothing when there are no selected elements, or when the first selected
-- | element does not have the specified attribute.
attr :: String -> Cheerio -> Maybe String attr :: String -> Cheerio -> Maybe String
attr = runFn4 attrImpl Nothing Just attr = runFn4 attrImpl Nothing Just

View File

@ -44,6 +44,10 @@ suites = do
(Just "fruits") (Just "fruits")
(loadRoot htmlEx # find "ul" # attr "id") (loadRoot htmlEx # find "ul" # attr "id")
Assert.equal
Nothing
(loadRoot htmlEx # find "ul" # attr "no-such-attribute")
Assert.equal Assert.equal
Nothing Nothing
(emptyCheerio # attr "id") (emptyCheerio # attr "id")