How do I get an element name in cheerio with node.js

こ雲淡風輕ζ 提交于 2019-12-02 08:09:25

问题


How do I get an element's name in cheerio?

The jQuery equivalent would be .attr('name') but that returns undefined in cheerio.


回答1:


There's only one case, I suppose, when $someElement.attr('name') returns undefined - if there's NO attribute name on that element. For example...

var cheerio = require('cheerio'),
    $ = cheerio.load(
      '<input id="one" type="input" /><input id="two" name="some_name" />');

console.log( $('#one').attr('name') ); // undefined
console.log( $('#two').attr('name') ); // some_name

Note that <name> attribute is only applicable to the following set of elements (MDN):

<a>, <applet>, <button>, <form>, <frame>, <iframe>, <img>, 
<input>, <map>, <meta>, <object>, <param>, <select>, <textarea>

To get the name of the element itself (it's tagName actually, but Cheerio abstracts it), use name property of the underlying element wrapped in Cheerio container, like this:

console.log( $('#one')[0].name ); // input 
console.log( $('#two')[0].name ); // input


来源:https://stackoverflow.com/questions/22937383/how-do-i-get-an-element-name-in-cheerio-with-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!