I have tried hours to get the results, but failed, below, I will post all I have done, hope I can get some tips, BTW,Thanks.
from the error message, yeah It's cssRules is null, surely error!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="index.css">
<title>css style</title>
<style type="text/css">
#demo {
font-size: 10px; /*first css rule */
}
p {
border: 1px solid green; /*second one*/
}
</style>
</head>
<body>
<div id="demo" style="color: red;">
<p>how to access of document's css!</p>
</div>
</body>
external css
#demo {
font-weight: 900;
}
p {
padding: 20px;
}
Javascript
<script>
/*1,to get the inline style, this maybe the most easy one*/
var cssInline = document.getElementById('demo').style;
var cssInText = cssInline.cssText, cssColor = cssInline.color;
console.log(cssInText, cssColor);
/*2.a to get the style in head*/
var cssInHeada = document.getElementById('demo');
// using the computed css of inline
var cssHeadText = getComputedStyle(cssInHeada, null);
console.log(cssHeadText);
// 2.b to get the style directly
var cssInHeadb = document.getElementsByTagName('style')[0];
console.log(cssInHeadb.textContent);
// 2.c or like this
var cssInHeadc = document.styleSheets[1];
console.log(cssInHeadc.cssRules[0].cssText); //per rule
/*3, but I cant get the extenal style*/
var cssExtenal = document.styleSheets[0];
console.log(cssExtenal.cssRules[0].cssText);
</script>
Thank your guys!
I suspect your JavaScript is running before the stylesheet is loaded. Try this:
document.addEventListener('DOMContentLoaded', function () {
var cssExtenal = document.styleSheets[0];
console.log(cssExtenal.cssRules[0].cssText);
}, false);
Or if you happen to be using jQuery, this is more universal:
$('document').ready(function(){
var cssExtenal = document.styleSheets[0];
console.log(cssExtenal.cssRules[0].cssText);
});
Update: another possibility is that you're using Chrome and either loading the CSS cross-domain or using the file:// protocol. This appears to be a known issue and is not considered a bug.
Related
I have made a game using JavaScript and I would like the background to change after the game is over or after isGamerOver = true to be more specific. Here is what I currently have. Right now when ever the game ends I get a Uncaught TypeError: Cannot read property 'style' of null.
function gameOver() {
console.log('game over')
isGamerOver = true
while (grid.firstChild) {
grid.removeChild(grid.firstChild)
}
grid.innerHTML = score
clearInterval(upTimerId)
clearInterval(downTimerId)
clearInterval(leftTimerId)
clearInterval(rightTimerId)
if(isGamerOver = true){
document.getElementById("grid").style.backgroundImage="url('backgrounds/background-up.png')";
}else{
document.getElementById("grid").style.backgroundImage="url('backgrounds/game-over.png')";
}
}
Here is the style sheet I am trying to change
.grid {
width: 400px;
height: 600px;
background-image: url(backgrounds/background-up.png);
position: relative;
font-size: 100px;
text-align: center;
color: #fff;
}
Here Is my HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8">
<title>100% Not Doodle Jump</title>
<link rel="stylesheet" href="style.css"></link>
<script src="app.js" charset="utf-8"></script>
</head>
<body>
<div class="grid"></div>
</body>
</html>
I also added a div in JavaScript
const grid = document.querySelector('.grid')
const doodler = document.createElement('div')
If you got your grid defined like that:
const grid = document.querySelector('.grid')
change this:
if(isGamerOver = true){
document.getElementById("grid").style.backgroundImage="url('backgrounds/background-up.png')";
}else{
document.getElementById("grid").style.backgroundImage="url('backgrounds/game-over.png')";
}
to this:
if(isGamerOver = true){
grid.style.backgroundImage="url('backgrounds/background-up.png')";
}else{
grid.style.backgroundImage="url('backgrounds/game-over.png')";
}
The javascript, html and css work in this jsfiddle
but when entered into an html file like so:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
var target = $(".mypara").offset().top;
var interval = setInterval(function() {
if ($(window).scrollTop() >= target) {
alert("made it!");
clearInterval(interval);
}
}, 250);
</script>
<style>
body {
background-color: linen;
height: 1000px;
}
p {
color: blue;
margin-top: 500px;
}
</style>
</head>
<body>
<p class="mypara">asdfasdfasf</p>
</body>
</html>
chrome console gives this error
Uncaught TypeError: Cannot read property 'top' of undefined(anonymous function) # index - Copy.html:8
This error refers to line 8:
var target = $(".mypara").offset().top;
Can someone help me understand why?
Wrap your code in
$(document).ready (function (){
// code here
});
You're trying to access an element in the DOM before it exists so when your trying to access the class the item doesnt exist yet. Or move your script below the elements in the html
Works in fiddle cause thet wrap you're code depending on your setting which defaults to domready I believe
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<style>
body {
background-color: linen;
height: 1000px;
}
p {
color: blue;
margin-top: 500px;
}
</style>
</head>
<body>
<p class="mypara">asdfasdfasf</p>
<p class="mypara">Include js files to be at the bottom so that it would be the one to be loaded accordingly</p>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
// if document is ready then
// its the only time to execute
// process withing the block
$(document).ready(function() {
var target = $(".mypara").offset().top;
var interval = setInterval(function() {
if ($(window).scrollTop() >= target) {
alert("made it!");
clearInterval(interval);
}
}, 250);
});
</script>
</body>
</html>
I'm starting to learn HTML5+CSS+JS. It was all going fine on my Windows desktop, but when I try doing something on my Linux notebook, no javascript seems to work.
This is the mini tutorial I followed: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/JavaScript
and this is my page with the result: http://www.lele.bbt.net.ar/prueba01/
(As you can see, the JS is not doing a thing).
// JavaScript demonstration
var changeBg = function(event) {
console.log("method called");
var me = event.target,
square = document.getElementById("square");
square.style.backgroundColor = "#ffaa44";
me.setAttribute("disabled", "disabled");
setTimeout(function() {
clearDemo(me)
}, 2000);
}
function clearDemo(button) {
var square = document.getElementById("square");
square.style.backgroundColor = "transparent";
button.removeAttribute("disabled");
}
var button = document.querySelector("button");
button.addEventListener("click", changeBg);
console.log(button);
#square {
width: 120px;
height: 120px;
border: 2px inset gray;
margin-bottom: 1em;
}
button {
padding: .5em 2em;
}
<!DOCTYPE html>
<html>
<head>
<title>Mozilla CSS Getting Started - JavaScript demonstration</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<h1>JavaScript sample</h1>
<div id="square"></div>
<button>Click Me</button>
</body>
</html>
(Here it works, but for some reason, not when I do it on my computer).
I don't know if it can be a priviledge problem or something like that (js has read/write priviledges, not execute. But I guess that's how it should be)
Thanks!
I'm pretty sure it's because the script can't find the button.
You load your script before everything else is loaded, which is fine. But you can have problems like this. To avoid this kind of problems you load the JavaScript file after the HTML.
At the moment if you try to print the var "button" you will receive "null".
The Chrome console when you open the page gives you this error:
Uncaught TypeError: Cannot read property 'addEventListener' of null
That means that it is trying to read the property of the button, which is null.
Move the script tag to the very end, just before the closing </body> tag:
<body>
<h1>JavaScript sample</h1>
<div id="square"></div>
<button>Click Me</button>
<script type="text/javascript" src="script.js"></script>
</body>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="20000;http://new-url/" id="meta-refresh">
<style type="text/css">
#test{
width: 100px;
height: 80px;
background-color: yellow;
opacity:0.5;
z-index:3;
}
</style>
<title>Add Properties</title>
<!--link rel="stylesheet" href="qunit-1.12.0.css"-->
</head>
<body>
<div id="test">This is some text</div>
<p>Properties</p>
<script>
function getStyle(el, cssprop){
if (el.currentStyle) //IE
return el.currentStyle[cssprop]
else if (document.defaultView && document.defaultView.getComputedStyle) //Firefox
return document.defaultView.getComputedStyle(el, "")[cssprop]
else //try and get inline style
return el.style[cssprop]
}
console.log("1"+navigator.appVersion);
console.log("2"+navigator.platform);
console.log("3"+history.length);
console.log("4"+parent.top.document.referrer);
metatags = document.getElementsByTagName("meta");
var content = metatags[0].getAttribute("content");
var mr = document.getElementById("meta-refresh");
console.log("Meta Refresh"+ content);
console.log(navigator.plugins);
console.log(navigator.plugins.length);
var mydiv = document.getElementById("test");
console.log(getStyle(mydiv,'width'));
console.log(getStyle(mydiv,'opacity'));
console.log(getStyle(mydiv,'z-index'));
var d = new Date()
var n = d.getTimezoneOffset();
console.log(n);
</script>
</body>
</html>
This is the code and all properties like width opacity show appropriate values but z-index gives out an undefined value.I tried 'z-index' as well as "zindex".Please help me with this problem.
Thanks in advance
Swaraj
I tried z-index as well as zindex
Close, but it's zIndex. Properties of CSSStyleDeclarations (such as returned by .style or getComputedStyle()) are camel-cased. You also could use .getPropertyValue("z-index").
I'm practicing basic JS skills by setting up little exercises for myself. In this one, I have a list of <a>s inside a div. The aim of the exercise is to wrap each <a> in a div. I'm using replaceChild in this instance.
Oddly (to me at least) the script works for the first three links, but after that throws an error:
Uncaught TypeError: Cannot read property 'parentNode' of undefined
I can't tell why the script partly works. Can anyone see what I'm doing wrong here? Here's the code I'm using:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style media="all">
div div {padding: 10px; background: #e7e7e7; margin: 5px;}
</style>
</head>
<body>
<div>
link
link
link
link
link
link
</div>
<script>
var links = document.getElementsByTagName("a");
for (var i=0, ii=links.length; i<ii; i++)
{
var container = document.createElement("div");
links[i].parentNode.replaceChild(container, links[i]);
container.appendChild(links[i]);
}
</script>
</body>
</html>
and here's an online version: http://codepen.io/anon/pen/Lpuky
I've tried the few debugging techniques that I know of and read about this error message, but haven't worked out what's wrong here. Seems funny to me that it works for 3 of the 6 links.
The collection links is NodeList and is live.
Since you are replacing them, they are disappearing from the collection and our index into them is no longer pointing to anything.
You're modifying the nodelist as you iterate over it. Use the Array slice method to make a copy of the list:
var linksCopy = Array.prototype.slice.call(links);
for (var i=0; i<linksCopy.length; i++)
{
var container = document.createElement("div");
linksCopy[i].parentNode.replaceChild(container, linksCopy[i]);
container.appendChild(linksCopy[i]);
}
Regarding your own follow-up answer: if your objective was simply to find the easiest way to wrap the <a>s in <div>s, rather than to practice with createElement, replaceChild or appendChild or any of the other methods, this would be it:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<style>
div div {
padding: 10px;
background: #e7e7e7;
margin: 5px;
}
</style>
</head>
<body>
<div>
link
link
link
link
link
link
</div>
<script>
var links = document.querySelectorAll("a");
for (var i=0; i<links.length; i++) {
links[i].outerHTML = '<div>'+links[i].outerHTML+'</div>';
}
</script>
</body>
</html>
.
Live demo here: http://jsbin.com/jasoho/1/edit?html,output. Another advantage of the outerHTML method is that it doesn't change the nodeList. So you can also use getElementsByTagName in stead of querySelectorAll.
As a follow up to this, I often hear that querySelectorAll() is different in that it returns a static Nodelist rather than an array, so I thought that might come in handy here, and indeed it does:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style media="all">
div div {padding: 10px; background: #e7e7e7; margin: 5px;}
</style>
</head>
<body>
<div>
link
link
link
link
link
link
</div>
<script>
var links = document.querySelectorAll("a");
for (var i=0, ii=links.length; i<ii; i++)
{
var container = document.createElement("div");
links[i].parentNode.replaceChild(container, links[i]);
container.appendChild(links[i]);
}
</script>
</body>
</html>
Also, an alternative to Array.prototype.slice.call(links) is [].slice.call(links):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style media="all">
div div {padding: 10px; background: #e7e7e7; margin: 5px;}
</style>
</head>
<body>
<div>
link
link
link
link
link
link
</div>
<script>
var links = document.getElementsByTagName("a");
var linksCopy = [].slice.call(links);
for (var i=0; i<linksCopy.length; i++)
{
var container = document.createElement("div");
linksCopy[i].parentNode.replaceChild(container, linksCopy[i]);
container.appendChild(linksCopy[i]);
}
</script>
</body>
</html>
And another option again is to use [].forEach.call():
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style media="all">
div div {padding: 10px; background: #e7e7e7; margin: 5px;}
</style>
</head>
<body>
<div>
link
link
link
link
link
link
</div>
<script>
[].forEach.call(document.querySelectorAll('a'), function(el) {
var container = document.createElement("div");
el.parentNode.replaceChild(container, el);
container.appendChild(el);
});
</script>
</body>
</html>
Yet another option, using Array.from():
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style media="all">
div div {padding: 10px; background: #e7e7e7; margin: 5px;}
</style>
</head>
<body>
<div>
link
link
link
link
link
link
</div>
<script>
var links = document.getElementsByTagName("a");
var linksCopy = Array.from(links);
for (var i=0; i<linksCopy.length; i++)
{
var container = document.createElement("div");
linksCopy[i].parentNode.replaceChild(container, linksCopy[i]);
container.appendChild(linksCopy[i]);
}
</script>
</body>
</html>