2016-12-31 110 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