2016-12-31 86 views
0

属性我有这样的HTML string在节点:合并HTML元素节点

<a data-style="width:32px" id="heilo-wrld" style="height:64px"> 
    Hello world 
</a> 

的代码有data-stylestyle属性我想在一个合并style属性是这样的:

<a id="heilo-wrld" style="width:32px; height:64px;"> 
    Hello world 
</a> 

我也可以有复杂的HTML块这样的:

<div class="wrapper" data-style="background-color: red;"> 
    <a data-style="width:32px" id="heilo-wrld" style="height:64px"> 
     Hello world 
    </a> 
</div> 

为了得到这样的结果:

<div class="wrapper" style="background-color: red;"> 
    <a id="heilo-wrld" style="width:32px; height:64px;"> 
     Hello world 
    </a> 
</div> 

我发现了一些插件,但它没有这样做的具体工作:

确实存在一些聪明如何做到这一点?

+1

为什么你需要从'HTML删除'数据 - *'属性'? – guest271314

+0

因为我需要它仅作为渲染HTML作为预览,也有一个情况我将在剪贴板复制HTML没有'数据style'属性(只是为了渲染目的而使用) – vitto

回答

2

使用jsdom,你可以定义一个mergeStyles功能是这样的:

const jsdom = require('jsdom'); 

function mergeStyles(html, callback) { 
    return jsdom.env(html, function(errs, window) { 
    const { document } = window; 

    Array.from(
     document.querySelectorAll('[data-style]') 
    ).forEach(function(el) { 
     const styles = []; 

     Array.from(el.attributes).forEach(function(attr) { 
     if (attr.name !== 'style' && attr.name !== 'data-style') { 
      return; 
     } 

     styles.push(attr.value); 

     el.removeAttributeNode(attr); 
     }); 

     if (!styles.length) { 
     return; 
     } 

     el.setAttribute('style', styles.join(';')); 
    }); 

    const result = document.body.innerHTML; 

    return callback(null, result); 
    }); 
} 

然后调用它像:

const input = ` 
    <div class="wrapper" data-style="background-color: red;"> 
     <a data-style="width:32px" id="heilo-wrld" style="height:64px"> 
      Hello world 
     </a> 
    </div> 
`; 

mergeStyles(input, function(err, result) { 
    if (err) { 
    throw err; 
    } 

    // `result` should contain the HTML with the styles merged. 
    console.log(result); 
}); 
+0

这是我需要什么,谢谢新年快乐! – vitto