cheerio icon indicating copy to clipboard operation
cheerio copied to clipboard

Can't set existing attribute as undefined

Open walshyb opened this issue 2 years ago • 1 comments

When setting an existing attribute to undefined on a Cheerio element, the the attribute does not get removed or set to undefined.

However, when setting the same attribute to null, the attribute gets removed from the element.

const $cheerio = cheerio.load('<ul><li class="pear" foo="bar">Pear</li></ul>');
const $pear = $cheerio('.pear');

// Setting attribute 'foo' to undefined
$pear.attr('foo', undefined);
const attr1 = $pear.attr('foo');

attr1 === 'bar'           // true
attr1 === undefined       // false
$pear.attr('foo')         // [Object: null prototype] { foo: 'bar' }

// Setting attribute 'foo' to null
$pear.attr('foo', null);
const attr2 = $pear.attr('foo');

attr2 === 'bar'           // false
attr2 === undefined       // true
att2 == null              // true
$pear.attr('foo')         // [Object: null prototype] { }

walshyb avatar Jul 28 '23 20:07 walshyb

undefined is treated as if no value is passed, and will result in a get call. I agree that that is surprising. Let's see what jQuery does and align with jQuery's behavior.

fb55 avatar Jul 29 '23 08:07 fb55