cheerio icon indicating copy to clipboard operation
cheerio copied to clipboard

`$.attr('value')` returns incorrect result for an `<option>` without a value attribute

Open 36degrees opened this issue 1 year ago • 0 comments

Steps to reproduce

const cheerio = require('cheerio')

const $ = cheerio.load(`
<select class="govuk-select" id="colors" name="colors">
  <option>Red</option>
  <option>Green</option>
  <option>Blue</option>
</select>
`)

console.log($('option:first-child').attr('value'))

Actual result

'Red' is logged to the console, which is the inner text of the option

Expected result

undefined should be logged to the console, because the element does not have a value attribute.

This would match how attr works both according to jQuery's documentation and when compared to it's actual behaviour (CodePen).

Further details

It looks like this may be caused by this code in the getAttrfunction:

https://github.com/cheeriojs/cheerio/blob/273789820ec281defd6854ab13df8f9fb9caaafc/src/api/attributes.ts#L64-L67

This was introduced as part of #671 but should probably have only affected the val function as described in the issue it was trying to fix.

I'd be open to raising a pull request with a fix if that would be helpful.

36degrees avatar Jun 09 '23 09:06 36degrees