如何在node.js中使用cheerio获取元素名称

4
我怎样在Cheerio中获取元素的名称?
在jQuery中,相当于.attr('name'),但是在Cheerio中会返回undefined。
1个回答

13

我想,只有一种情况会导致$someElement.attr('name')返回undefined——如果该元素上没有属性name。例如...

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

请注意,<name> 属性仅适用于以下一组元素(MDN):
<a>, <applet>, <button>, <form>, <frame>, <iframe>, <img>, 
<input>, <map>, <meta>, <object>, <param>, <select>, <textarea>

要获取元素本身的名称(实际上是 tagName ,但 Cheerio 将其抽象化),请使用包含 Cheerio 容器中的基础元素的 name 属性,如下所示:
console.log( $('#one')[0].name ); // input 
console.log( $('#two')[0].name ); // input

1
我要查找的是元素名称而不是属性名称。例如:<input /> = "input" - dataphile
1
然后,就像我说的那样,你应该使用 $('someSelector')[0] .name - raina77ow

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接