cheerio
cheerio copied to clipboard
Can't set existing attribute as undefined
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] { }
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.