webmasternewbie
webmasternewbie

Reputation: 167

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.

Upvotes: 6

Views: 3862

Answers (5)

ABHIJITH GM
ABHIJITH GM

Reputation: 134

document.styleSheets is an array , for each of the style definition in your page . 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

Upvotes: 2

Ja9ad335h
Ja9ad335h

Reputation: 5075

document.getElementsByTagName returns Array of Elements

so you need to access it with index

document.getElementsByTagName('style')[0].innerHTML

document.styleSheets is much useful if you want to get specific selector or modify something from style sheet

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';
    }    
}

Upvotes: 10

webmasternewbie
webmasternewbie

Reputation: 167

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.

Thank you guys! And sorry for this newbie question... all day codding, my eyes are hurting, coffee time.

Upvotes: 0

mediaguru
mediaguru

Reputation: 1917

<!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/

Upvotes: 1

hardik
hardik

Reputation: 388

using jquery use this

var x = $('style').html();

using javascript

var x=document.getElementById("home");

var y = x.firstChild.innerHTML;

Upvotes: 0

Related Questions