[英]JS - how to get content of internal style element (<style>…</style)
by internal style I mean我的意思是内部风格
<style>
#div
{color:red;}
</style>
document.getElementsByTagName('style').innerHTML is not working... document.styleSheets either. document.getElementsByTagName('style').innerHTML 不工作...... document.styleSheets 也是。
document.getElementsByTagName
returns Array of Elements document.getElementsByTagName
返回元素数组
so you need to access it with index
所以你需要用
index
访问它
document.getElementsByTagName('style')[0].innerHTML
document.styleSheets
is much useful if you want to get specific selector or modify something from style sheet如果您想获取特定选择器或从样式表修改某些内容,
document.styleSheets
非常有用
Example例子
var styleSheet = document.styleSheets[1];
// assuming second one is embedded style,
// since document.styleSheets also shows linked style sheets (like <link heref=".. >)
for (var i = 0; i < styleSheet.rules.length; i++) {
// if you are looking for selector '.main'
if (styleSheet.rules[i].selectorText === '.main') {
// get background color
var oldBg = styleSheet.rules[i].style.backgroundColor;
// set background color
styleSheet.rules[i].style.backgroundColor = '#ddd';
}
}
document.styleSheets
is an array , for each of the style definition in your page . document.styleSheets
是一个数组,用于页面中的每个样式定义。 Iterate for each of the style elements and find the rules defined.迭代每个样式元素并找到定义的规则。
document.styleSheets[0].rules
This is again an array.这又是一个数组。 so iterate .
所以迭代。 The rule text for each of the rules can be extracted as follows
每个规则的规则文本可以提取如下
document.styleSheets[indexofstyleelement].rules[indexofrule].cssText
document.styleSheets[0].rules[0].cssText
gives rule text for first of the rules defined inside first style element document.styleSheets[0].rules[0].cssText
给出第一个样式元素中定义的第一个规则的规则文本
<!DOCTYPE html>
<html>
<head>
<style>
#div {
color: red;
}
</style>
</head>
<body>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementsByTagName("STYLE")[1];
document.getElementById("demo").innerHTML = x.innerHTML;
}
</script>
</body>
</html>
https://jsfiddle.net/mediaguru/xt9mkncx/ https://jsfiddle.net/mediaguru/xt9mkncx/
using jquery use this使用 jquery 使用这个
var x = $('style').html();
using javascript使用 JavaScript
var x=document.getElementById("home");
var y = x.firstChild.innerHTML;
Ahh I'm so stupid..啊啊啊我好笨啊。。
for (var i = 0; i < styles_length; i++)
{// I had:
// styles.innerHTML;
// not correct:
styles[i].innerHTML;
}
All answers by @Jag, @ABHIJITH GM, @mediaguru, @hardik are correct. @Jag、@ABHIJITH GM、@mediaguru、@hardik 的所有答案都是正确的。
Thank you guys!谢谢你们! And sorry for this newbie question... all day codding, my eyes are hurting, coffee time.
很抱歉这个新手问题......整天编码,我的眼睛很痛,咖啡时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.