How do I get my current page stylesheet as a string? - javascript

Let's say my current page looks like:
<html>
<head>
<style>
/* I want to get all this as a string.. AS IS */
</style>
</head>
<body>
<script>
function getEntireStyleAsString()
{
var str = "";
/// .... what should be in here?
return str;
}
</script>
</body>
</html>
I'd like a simple function that returns my entire style of my page as a string. Using jquery is fine. I've been researching this for awhile and can't find the answer.

If you just want the first stylesheet on the page you can use the following:
var ele = document.getElementsByTagName('style')[0].innerHTML;
However this will only get the code within that first style tag.

If using jQuery is allowed, you can write something like this:
var styles = $('style');
Which gives a jQuery selection of all styles on the document.
From here, you can do something like:
styles.text();
To get it all as a string. Good luck!

You may use the answer provided by Peter Rasmussen. But if you have more than one <style> tags in your <head> section, you would better use this to pull all styles:
var sts = document.getElementsByTagName('style');
var str = '';
for(i = 0; i < sts.length; i++){
str = str + sts[i].innerHTML;
}
document.write(str);

Got it, nevermind.
<style id='test'>
</style>
$('#test').text()

Related

Run JavaScript inside <script src="..."></script> Tags?

I've a JavaScript file that processes tab switches. Here is the source:
var tCount = 0;
function SwitchToTab(id) {
if (id < 0 || id > tCount) { id = 0; }
for (var i = 0; i < tCount; i++) { document.getElementById("tab" + i).className = ""; }
document.getElementById("tab" + id).className = "active";
for (var i = 0; i < tCount; i++) { document.getElementById("area" + i).style.display = "none"; }
document.getElementById("area" + id).style.display = "";
}
function InitializeTabs(initialTabId, tabsCount) {
tCount = tabsCount;
SwitchToTab(initialTabId);
}
I'm trying to make it as short as possible like this:
<script src="Resources/Tabs.js">InitializeTabs(0, 4);</script>
It doesn't works but it works if I separate them like this:
<script src="Resources/Tabs.js"></script>
<script>InitializeTabs(0, 4);</script>
So, is there any way to run JavaScript inside <script src="..."></script> tags? What I am missing?
No, this is not possible. The html spec dictates that a <script> tag does one or the other.
<script>Tag Html Spec, emphasis mine.
The script may be defined within the contents of the SCRIPT element or in an external file. If the src attribute is not set, user agents must interpret the contents of the element as the script. If the src has a URI value, user agents must ignore the element's contents and retrieve the script via the URI.
You are suppose to do it the second way. in <script src="Resources/Tabs.js">InitializeTabs(0, 4);</script> you are referencing an external javascript file, your inline code should go into a second script block.
You can either use src, or put JavaScript inside the tag.
But not both at once. There's no downside to using two tags anyway (apart from larger file size).
When you include <script src="Resources/Tabs.js"></script>, you are mentioning that you want to use the Javascript which is included inside the Tabs.js file so that the compiler knows where to look for InitializeTabs function, when it is trying to execute the function.
Now if you want to include some Javascript inline, that is inside the HTML, hen you use the <script>... JAVASCRIPT HERE .... </script>
You need to do it like this
<script src="Resources/Tabs.js"></script>
<script>InitializeTabs(0, 4);</script>
You can't put javascript inside of <script src="... tags, but you could run a JavaScript file which parses the HTML, looking for <script src tags, which converts it into two tags.
For example,
<script src="Resources/Tabs.js">InitializeTabs(0, 4);</script>
would have to be converted into
<script src="Resources/Tabs.js"></script>
<script>InitializeTabs(0, 4);</script>
Here's the code I tried:
var tags = document.querySelectorAll("script[src]");
[].forEach.call(tags, function(elem){
var text = elem.innerText;
var src = elem.src;
var parent = elem.parentNode;
parent.removeChild(elem);
var newTag = document.createElement('script');
newTag.setAttribute('src', src);
parent.appendChild(newTag);
var newTag = document.createElement('script');
var t = document.createTextNode(text);
newTag.appendChild(t);
parent.appendChild(newTag);
});
in a JSFiddle

How to make a crossword in javascript

I am new to all this javascript, I was trying to make a crossword. I want a webpage that automatically makes 485 divs inside another div when the page loads. How is it possible to do this with a for loop?
I can see you are new to Stackoverflow as well as Javascript. So...I'll cut you some slack and answer (com'n guys...give a new guy a break).
For future questions, I highly recommend checking out https://stackoverflow.com/help/how-to-ask. It'll help you get prompt, accurate answers. Welcome to Stackoverflow.
http://jsbin.com/nazuwoqe/1/edit
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="myContainer"></div>
<script>
var element;
var body = document.getElementById('myContainer');
for(var i=0; i<485; i++) {
element = document.createElement("div");
element.innerHTML = i;
body.appendChild(element);
}
</script>
</body>
</html>
A crossword puzzle isn't going to be a simple project to create. I recommend starting with some more basic tasks and tutorials.
Try this
var BigDiv = document.createElement('div');
// specify BigDiv's param like id, class etc. here
var TinyDiv;
for (i = 0; i < 485; i++) {
TinyDiv = document.createElement('div');
// specify TinyDiv's param like id, class etc. here
BigDiv.appendChild(TinyDiv)
}
//put your BigDiv where you want to, here it's in body
document.getElementsByTagName('body')[0].appendChild(BigDiv);

Set entire page's css on click?

Does anyone know how I can change the entire document's CSS file on click? I've searched around but only found a few results on setting a class/ID's CSS, not the entire document. My website has two themes, light/dark, and I want to load up "light.css" or "dark.css" from two links.
Thanks.
You need to change the src of the the link tag, which controls the styles. For example, you probably have this in your head tag:
<link rel="stylesheet" href="light.css">
You need to change the href attribute of the link tag to "dark.css" when you click something. You can do that like this:
document.getElementById('id-of-element').addEventListener('click',function(){
document.getElementsByTagName('link')[0].setAttribute('href',isDark?'light.css':'dark.css');
isDark=isDark?false:true;
}
IMPORTANT: you need to set isDark to false or true before this code, depending on whether the page is supposed to be dark or light in the beginning. You also need to change id-of-element to the id of the element that should be clicked to toggle the state of the page.
I think this is better than the other answers because it is simpler and uses no jquery.
EDIT: I accidentally had the src attribute instead of the href one before. I now updated it to be correct.
Yeah, you can do using theming. But the changing of CSS is limited to the <body> tag.
$("a.theme").click(function(){
$("body").addClass("dark");
});
I have used jQuery library to make the coding easier. And it is not a good idea to switch CSS rather, you can change the classes.
Demo
You can check out the working demo in jsBin.
Check out this answer for more details: Selecting a web page look and feel without reloading, with one CSS.
Try something like this:
Light
Dark
<script type="text/javascript" charset="utf-8">
$('a#light, a#dark').click(function(){
$('style').remove();
$.ajax({
url:'http://www.example.com/' + $this.attr('id') + '.css',
success:function(data){
$('<style></style>').appendTo('head').html(data);
}
})
})
</script>
Of course, you need to load jQuery first.
There's 2 ways that come immediately to mind.
1) Add a style tag to the page's head, ensuring that the style tag has a unique id. You can then set the innerHTML of that element. (somewhat messy)
2) Add a link tag to the page's head, also ensuring that it has a unique id. You set the type='text/css' and the rel='stylesheet' attributes. You the set the src of this link element to the appropriate css file.
Here's an example of each type. Just supply css files for theme3() and theme4() functions.
Example:
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
function toggleClass(element, newStr)
{
index=element.className.indexOf(newStr);
if ( index == -1)
element.className += ' '+newStr;
else
{
if (index != 0)
newStr = ' '+newStr;
element.className = element.className.replace(newStr, '');
}
}
function forEachNode(nodeList, func)
{
var i, n = nodeList.length;
for (i=0; i<n; i++)
{
func(nodeList[i], i, nodeList);
}
}
window.addEventListener('load', mInit, false);
function mInit()
{
var style = newEl('style');
style.setAttribute('id', 'dynCss');
document.head.appendChild(style);
var style2 = newEl('link');
style2.setAttribute('type', 'text/css');
style2.setAttribute('rel', 'stylesheet');
style2.setAttribute('id', 'dynCss2');
document.head.appendChild(style2);
}
function theme1()
{
var style = byId('dynCss');
style.innerHTML = "h1{color: red;}";
var style2 = byId('dynCss2');
style2.setAttribute('href', '');
}
function theme2()
{
var style = byId('dynCss');
style.innerHTML = "h1{color: blue;}";
var style2 = byId('dynCss2');
style2.setAttribute('href', '');
}
function theme3()
{
var style = byId('dynCss');
style.innerHTML = "";
var style2 = byId('dynCss2');
style2.setAttribute('href', 'style3.css');
}
function theme4()
{
var style = byId('dynCss');
style.innerHTML = "";
var style2 = byId('dynCss2');
style2.setAttribute('href', 'style4.css');
}
</script>
<style>
</style>
</head>
<body>
<h1>This is the heading</h1>
<input type='button' onclick='theme1();' value='Theme 1'/>
<input type='button' onclick='theme2();' value='Theme 2'/>
<input type='button' onclick='theme3();' value='Theme 3'/>
<input type='button' onclick='theme4();' value='Theme 4'/>
</body>
</html>

Javascript Onclicks not working?

I have a jQuery application which finds a specific div, and edit's its inner HTML. As it does this, it adds several divs with onclicks designed to call a function in my JS.
For some strange reason, clicking on these never works if I have a function defined in my code set to activate. However, it works fine when calling "alert("Testing");".
I am quite bewildered at this as I have in the past been able to make code-generated onclicks work just fine. The only thing new here is jQuery.
Code:
function button(votefor)
{
var oc = 'function(){activate();}'
return '<span onclick=\''+oc+'\' class="geoBut">'+ votefor +'</span>';
}
Elsewhere in code:
var buttons = '';
for (var i = 2; i < strs.length; i++)
{
buttons += button(strs[i]);
}
var output = '<div name="pwermess" class="geoCon"><div class="geoBox" style=""><br/><div>'+text+'</div><br/><div>'+buttons+'</div><br/><div name="percentages"></div</div><br/></div>';
$(obj).html(output);
Elsewhere:
function activate()
{
alert("Testing");
}
You may want to take a look at jQuery.live(eventType, eventHandler), which binds an event handler to objects (matching a selector) whenever they are created, e.g.:
$(".somebtn").live("click", myClickHandler);
Follows a dummy example, may be this can help you.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script src="http://cdn.jquerytools.org/1.2.5/jquery.tools.min.js"></script>
<script type="text/javascript">
$(function() {
$('.go-right').click(function(){
c="Hello world";
$("#output").html(c);
});
});
</script>
</head>
<body >
<div id="output"></div>
<a class="go-right">RIGHT</a>
</body>
</html>
Change this:
var oc = 'function(){activate();}'
To be this instead:
var oc = 'activate();'

Javascript createElement() not working in Chrome

Javascript createElement() is not working in Chrome but it works in IE and Firefox fine. Why?
It's working perfectly, use this code:
var catDiv = document.createElement("div");
catDiv.innerHTML = "Test";
document.body.appendChild(catDiv);
Another working example (if you have an element with Id = myTableBody in your HTML)
var appendingTo = document.getElementById("myTableBody");
var tr = document.createElement("tr");
tr.setAttribute("name", "i");
appendingTo.appendChild(tr);
var name = document.createElement("Div" );
will work. And later you can add the attributes like
name.colSpan="2";
document.body.appendChild(name);
Note: don't try to use angular brackets like createElement("<div />").
It will not work in Chrome.
Edit: syntax issue in above code fixed. there should be a dot instead of comma.
Beacause your code is messed up, there's nothing wrong with "createElement":
<html>
<head>
<meta charset = "utf-8">
<title></title>
<script>
window.onload = function () {
for (var i = 0; i < 100; i ++) {
var div = document.createElement ("div");
div.style.border = "1px solid black";
div.style.margin = "20px";
div.style.padding = "10px";
document.body.appendChild (div);
}
}
</script>
<style></style>
</head>
<body></body>
</html>
So I also couldn't get createElement() to work in chrome. After reading Caio's post and testing the code provided I figured out what I was doing wrong.
On w3schools.com the examples they provide always use the tag name in all caps ex. createElement("DIV"), which is the way I was using it and with poor results.
After changing from "DIV" to "div" in my own code it instantly worked.
Thanks Caio.

Categories

Resources