jquery – 如何使用cheerio展开子元素?

我正在使用node.js.

我正在使用cheerio html解析器来读取html文档.

在这个例子中

 <div class="a b c">
      <a id="ddd"/>
      sample
 </div>

我试过这个

  var cheerio = require('cheerio');
  var c$= cheerio.load(/*html content*/);
  var cntext = c$('div').html();

cntext包含所需的div及其所有子项.

如何删除div并仅保留子节点?

提前致谢.

最佳答案 使用jquery的简单解决方案

You can simply convert it to html element using $(HTML_SSTRING_VAR) to create a html and use .html() function to get innerHTML like in the first case
can use

var s=$( "#Div" ).html();
var temp=$(s);
alert(temp.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id="Div">
 
<div class="demo-container">
  <div class="demo-box">Demonstration Box</div>
</div>
  </div>

最简单的纯JavaScript解决方案

Just find the substring between last occurrence of “<” and first occurrence of “>”
which would be the content assuming that native javscript functions should work perfectly .

Javscript Substring Function Documentation

var s=$( "#Div" ).html();
s = s.substring(s.indexOf(">")+1,s.lastIndexOf("<")-1);
alert(s);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id="Div">

<div class="demo-container">
  <div class="demo-box">Demonstration Box</div>
</div>
  </div>

另一种简单的方法

Just Create a div append the html content inside it and access the required content as innerHTML of the child div in the process we by pass the div which was to be eliminated

innerHTML Documentation

Children Documentation

var s=$( "#Div" ).html();
var temp = document.createElement('div');
temp.innerHTML = s;
alert(temp.children[0].innerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id="Div">

<div class="demo-container">
  <div class="demo-box">Demonstration Box</div>
</div>
  </div>
 

.unwrap()Returns: jQuery Description: Remove the parents of the set of
matched elements from the DOM, leaving the matched elements in their
place.
07003

ALL IN ONE FIDDLE

点赞