如何使用cheerio从根元素中选择直接子元素

问题描述 投票:0回答:1

假设您有以下设置(其中的数字仅供参考,应忽略):

const html = `
<div 1>
  <div>...</div>
  <div 2>...</div>
  <div>...</div>
  ...
</div>`;
$ = cheerio.load(html, null, false);

三个点还可以包含嵌套的div和其他html!

如何选择div 1?我试过了

  $(':scope')     -> null
  $('>div')       -> null

由于某种原因,我无法选择第一个/根 div。 但即使这是有道理的,你将如何选择它的直接子代 (div 2)。我试过了

 $(':scope>div')              -> null
 $().children().eq(1)         -> null
 $(':scope').children().eq(1) -> null

我的印象是

:scope
并没有像我想象的那样。有什么建议吗?

javascript html cheerio
1个回答
0
投票

我不确定你为什么要这样做,而且结构很不寻常(通常有一些识别特征——属性或你可以使用的一些结构),但以下应该有效:

$("div:first-of-type"); // if you know it's a div
$("*:first-of-type"); // if you have no idea what the root is
© www.soinside.com 2019 - 2024. All rights reserved.