Setting a data attribute using attr throws TypeError: Cannot read property 'test' of undefined.
$('ul').attr('data-url', 'http://www.example.com');
Error Stack
TypeError: Cannot read property 'test' of undefined
at Object.$.each (D:\node\frix\lib\html-creator.js:141:39)
at exports.each (D:\node\frix\node_modules\cheerio\lib\api\traversing.js:300:24)
at HTMLCreator.insertContent (D:\node\frix\lib\html-creator.js:131:12)
at HTMLCreator.resolveElements (D:\node\frix\lib\html-creator.js:56:10)
at promises.push.access.readElement.then.template (D:\node\frix\lib\html-creator.js:113:23)
at tryCallOne (D:\node\frix\node_modules\promise\lib\core.js:37:12)
at D:\node\frix\node_modules\promise\lib\core.js:123:15
at flush (D:\node\frix\node_modules\asap\raw.js:50:29)
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
Could you provide some more context?
require('cheerio')('<div>').attr('data-url', 'http://www.example.com')
works as expected for me.
@fb55
let cheerio = require('cheerio')
let $ = cheerio.load('<h2 class="title" data-foo=bar>Hello world</h2>')
$('h2').data('foo') // 'bar'
$('h2').data('foo', 'newbar')
$('h2').data('foo') // 'newbar'
$('h2').attr('data-a', 'b')
$.html() // '<h2 class="title" data-foo="bar" data-a="b">Hello world</h2>'
The data-foo attr in html() output is still the old value 'bar'.
@weijarz This is explicitly wanted. The data method does not interfere with data attributes, use attr to archieve that.
@fb55 seems like you could close this issue? if you want some help with triaging I could possibly lend some assistance
@jcrben Thanks a lot for the offer! I agree that this can be closed, just wanted to wait for a possible answer.
We should definitely have an easier onramp for people that want to help. For now I've tagged some PRs with Review, would be great if you could have a look at them. (Looking through the issues is also an immense help, but potentially not super exciting.) Happy to help if there is something else you would be interested in working on!
I was also tripped up by this. According to the documentation, one would think that setting data attributes is possible with data.
The snippet for data() reads:
Method for getting and setting data attributes. Gets or sets the data attribute value for only the first element in the matched set.
So I was surprised when element.data('key', 'value') doesn't change the value.
@drsnyder even if it says something else in the documentation, it is standard jquery behavoir, took me some time to figure out.
Most helpful comment
I was also tripped up by this. According to the documentation, one would think that setting data attributes is possible with
data.The snippet for
data()reads:So I was surprised when
element.data('key', 'value')doesn't change the value.