From ff5d1c3b224534d75822caf92060fc4127732c2f Mon Sep 17 00:00:00 2001 From: Gareth Daniel Smith Date: Sun, 29 Jul 2018 14:55:58 +0100 Subject: [PATCH] Deal with the case where the first element does not have the requested attribute: return Nothing rather than undefined. --- src/Cheerio.js | 8 +++++++- src/Cheerio.purs | 3 ++- test/Test/Cheerio.purs | 4 ++++ 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/Cheerio.js b/src/Cheerio.js index 73ec97e..cc32335 100644 --- a/src/Cheerio.js +++ b/src/Cheerio.js @@ -2,7 +2,13 @@ const cheerio = require('cheerio') // Attributes 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) { diff --git a/src/Cheerio.purs b/src/Cheerio.purs index 888ab8c..4386ddb 100644 --- a/src/Cheerio.purs +++ b/src/Cheerio.purs @@ -10,7 +10,8 @@ foreign import attrImpl :: forall a. Fn4 (Maybe a) (a -> Maybe a) String Cheerio (Maybe String) -- | 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 = runFn4 attrImpl Nothing Just diff --git a/test/Test/Cheerio.purs b/test/Test/Cheerio.purs index c4d0e30..fdd6eb3 100644 --- a/test/Test/Cheerio.purs +++ b/test/Test/Cheerio.purs @@ -44,6 +44,10 @@ suites = do (Just "fruits") (loadRoot htmlEx # find "ul" # attr "id") + Assert.equal + Nothing + (loadRoot htmlEx # find "ul" # attr "no-such-attribute") + Assert.equal Nothing (emptyCheerio # attr "id")