Retrieving all attributes of an Element
See original GitHub issueI recently needed to retrieve all attributes of an Element to loop through the elements. After awhile of beating my head against the tutorials on doing this with jQuery (e.g. use the .attributes object) I remembered that Cheerio doesn’t implement everything …
I did find inside one of the source files that the $(element) object has a .attribs array and was able to write my code to access that array. But it’s not compatible with the existing suggestions out there for using jQuery API approaches.
For example http://stackoverflow.com/questions/2048720/get-all-attributes-from-a-html-element-with-javascript-jquery
var element = $("span[name='test']");
$(element[0].attributes).each(function() {
console.log(this.nodeName+':'+this.nodeValue);});
What I did instead is:
var elem = $(element).get(0);
// attribs is an implementation detail of Cheerio
for (var nm in elem.attribs) {
var attr = elem.attribs[nm];
....
}
Seems to me that at the time you create the .attribs array, you could also/instead create a compatible .attributes object.
Issue Analytics
- State:
- Created 8 years ago
- Reactions:6
- Comments:5 (1 by maintainers)
Top GitHub Comments
Here is a wrapper that can be used between jQuery and Cheerio code:
Then instead of using directly
element.attributes
, you dogetAllAttributes(element)
. The API of the returned attributes is the same as forelement.attributes
.Example (usage with cheerio):
Edit: after @bogem comment, updated with a Cheerio working example, and an implementation without Lodash/
_
.Supporting the entire DOM API is what jsdom is for, cheerio (probably) won’t implement the
attributes
interface. You are in luck, though:attribs
is already an object, with the attribute name as the key and the value as the entry for the key.