cheeriojs / cheeriojs/cheerio

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

Open
#3,237 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
30.5k
Forks
1.7k
Avg merge
5h
Merged PRs (30d)
71

Description

## Steps to reproduce

```js
const cheerio = require('cheerio')

const $ = cheerio.load(`

Red
Green
Blue

`)

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](https://api.jquery.com/attr/) and when compared to [it's actual behaviour (CodePen)](https://codepen.io/36degrees/pen/QWJwvJG?editors=1111).

## Further details

It looks like this may be caused by this code in the `getAttr`function:

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](https://github.com/cheeriojs/cheerio/issues/633) it was trying to fix.

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

Contributor guide

Open the contributing guide

Research direction

Start in src/api/attributes.ts at the getAttr implementation around lines 64–67, then reproduce the option example from the issue. Review the behavior introduced by #671 and the context in #633; done means attr('value') returns undefined when the attribute is absent while the related val behavior remains correct.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, jquery, typescript
Domain
api, web-dev
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
50/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.