如何从html中删除所有属性?

Pav*_*nar 4 html javascript text-processing text-parsing node.js

我有原始的html,里面有一些css类用于各种标签.

例:

输入:

<p class="opener" itemprop="description">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque molestias natus iste labore a accusamus dolorum vel.</p>
Run Code Online (Sandbox Code Playgroud)

我想得到简单的HTML:

输出:

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque molestias natus iste labore a accusamus dolorum vel.</p>
Run Code Online (Sandbox Code Playgroud)

我不知道这些类的名字.我需要在JavaScript(node.js)中执行此操作.

任何的想法?

ade*_*neo 12

正如我在评论中指出的那样,这可以通过Cheerio来完成.
要删除所有元素的所有属性,您需要执行以下操作:

var html = '<p class="opener" itemprop="description">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque molestias natus iste labore a accusamus dolorum vel.</p>';

var $ = cheerio.load(html);   // load the HTML

$('*').each(function() {      // iterate over all elements
    this.attribs = {};     // remove all attributes
});

var html = $.html();          // get the HTML back
Run Code Online (Sandbox Code Playgroud)

  • 完美,这太棒了!非常感谢.:) (2认同)

Mat*_*ant 5

我将使用标签名称和innerHTML该元素的 来创建一个新元素。然后,您可以用新元素替换旧元素,或者使用newEl下面的代码执行任何您喜欢的操作:

// Get the current element
var el = document.getElementsByTagName('p')[0];

// Create a new element (in this case, a <p> tag)
var newEl = document.createElement(el.nodeName);

// Assign the new element the contents of the old tag
newEl.innerHTML = el.innerHTML;

// Replace the old element with newEl, or do whatever you like with it
Run Code Online (Sandbox Code Playgroud)

  • 如何在没有 DOM 的情况下创建元素(这就是 Node)? (2认同)