简体   繁体   English

如何分隔HTML元素和CSS元素并返回它们?

[英]How can I separate the HTML Elements and the CSS elements and return them?

This is a JS fiddle of one part I want to achieve. 这是我要实现的一部分的JS小提琴。

JS Fiddle JS小提琴

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

This returns the DOM structure like: 这将返回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>

I will be adding the div s dynamically and the CSS will be inline . 我将动态添加div ,CSS将inline Ideally, I want to be able to take the CSS out so I can return both the div elements and then the CSS attributes separately as text elements. 理想情况下,我希望能够取出CSS,以便可以分别返回div元素和CSS属性作为文本元素。

You can remove style attributes and store them in some id-style map, so you can use them later if you need. 您可以删除样式属性并将其存储在某些id样式映射中,因此以后可以根据需要使用它们。 Something like this: 像这样:

 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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 React 操作 HTML 元素并设置它们的样式 - How can I manipulate HTML elements with React and style them 如何使用 HTML/CSS 拖放元素? - How can I drag and drop elements with HTML/CSS? 如何选择这些元素并将其包装? - How can I select these elements and wrap them? 如何使用 javascript、html 和/或 css 获取两个元素并将它们居中? - How do I take two elements and center them together using javascript, html, and/or css? 隐藏几个HTML元素并显示它们或将它们附加到单独的部分 - Hide several HTML elements and show them or append them to a separate section 如何选择数组的多个html元素并将它们全部一次设置为一个函数? - How can I select multiple html elements of an array and set them all to a function at once? 我如何才能打开一个新窗口并将其仅传递给带有Javascript的选定html元素(以供以后打印它们使用)? - How can I open a new window and pass to it (for the later purpose of printing them) only selected html elements with Javascript? 我如何通过单击其中之一通过js或jquery交换html中的两个元素? - how can i interchange of two elements in html via js or jquery on click one of them? 如何有条件地加载 HTML 元素,或在加载页面之前删除它们? - How can I conditionally load HTML elements, or remove them BEFORE the page is loaded? 当所有元素都悬停时,CSS在悬停时更改单独的元素 - CSS changing separate elements on hover while all of them are hovered
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM