Skip to content

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

@36degrees

Description

@36degrees

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:

// Mimic the DOM and return text content as value for `option's`
if (elem.name === 'option' && name === 'value') {
return text(elem.children);
}

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions