Deal with the case where the first element does not have the
requested attribute: return Nothing rather than undefined.
This commit is contained in:
parent
4145c4634c
commit
ff5d1c3b22
@ -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) {
|
||||||
|
@ -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
|
||||||
|
|
||||||
|
@ -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")
|
||||||
|
Loading…
Reference in New Issue
Block a user