2015-04-26 77 views
2

這是我想要實現的一部分的JS小提琴。如何分離HTML元素和CSS元素並返回它們?

JS Fiddle

alert($("#content")[0].outerHTML); 

這將返回象DOM結構:

<div id="content"> 
    <div id="example1" style="width:100px height:100px background-color:red"></div> 
    <div id="example2" style="width:50px height:50px background-color:blue"></div> 
    <div id="example3" style="width:25px height:25px background-color:yellow"></div> 
</div> 

我將動態添加div S和CSS將inline。理想情況下,我希望能夠取出CSS,以便我可以將div元素和CSS屬性分別作爲文本元素單獨返回。

+0

這不是很清楚,但如果你想刪除的樣式** **屬性,你可以做'$( 「#內容」)的兒童。 ().removeAttr('style')' – adeneo

+0

你可以用例子指定你需要的輸出嗎? – vinayakj

+0

我想出了你的代碼行,謝謝。我用 'alert($(「#content」)。children()。attr(「style」));' – SamC

回答

0

您可以刪除樣式屬性並將它們存儲在某個id樣式的地圖中,以便您可以稍後根據需要使用它們。事情是這樣的:

var styles = {}; 
 

 
$("#content").children().each(function() { 
 
    styles[this.id] = $(this).attr('style'); 
 
    $(this).removeAttr('style'); 
 
}); 
 

 
// Check 
 
alert(
 
    'HTML:\n\n' + 
 
    $("#content")[0].outerHTML + 
 
    '\n\nCSS:\n\n' + 
 
    JSON.stringify(styles, null, 4) 
 
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="content"> 
 
    <div id="example1" style="width:100px height:100px background-color:red"></div> 
 
    <div id="example2" style="width:50px height:50px background-color:blue"></div> 
 
    <div id="example3" style="width:25px height:25px background-color:yellow"></div> 
 
</div>

+0

這個作品完全謝謝你! – SamC