Javascript not logging length correctly [duplicate] - javascript

This question already has answers here:
Is Chrome’s JavaScript console lazy about evaluating objects?
(7 answers)
Closed 7 years ago.
I'm having this issue with javascript right now where if I would console log the element itself it will show the length in chrome but it doesn't show the length correctly when I use .length.
Chrome console
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Hello World - Google Web Search API Sample</title>
<script src="https://www.google.com/jsapi"
type="text/javascript"></script>
<script language="Javascript" type="text/javascript">
google.load('search', '1');
function OnLoad() {
var searchControl = new google.search.SearchControl();
var localSearch = new google.search.LocalSearch();
searchControl.addSearcher(new google.search.WebSearch());
localSearch.setCenterPoint("New York, NY");
searchControl.draw(document.getElementById("searchcontrol"));
searchControl.execute("a");
}
google.setOnLoadCallback(OnLoad);
</script>
</head>
<body onLoad="myFunction()">
<div id="searchcontrol">Loading</div>
<script>
function myFunction() {
var y = document.getElementsByClassName('gsc-webResult gsc-result');
var y2 = y.length;
console.log(y);
console.log(y2);
}
</script>
</body>
</html>
As seen above I'm saving the element in var y and saving the length of y in y2. Then I'm console logging these variables, but it doesn't show the right length.
I'm not sure what the problem is here, I hope you can help.
Edit: Added working source code.

var y = document.getElementsByClassName('gsc-webResult gsc-result');
Returns an array of all the elements that match your query. Therefore y.length shows you the length of the array, not the length of the element.
try y[0] assuming that the element you want is first element in the array. Then length on the value assuming you want length of the text.
Also, if you only need a single element you may want to make your query more specific - but it's hard to say since you didn't post the corresponding DOM tree.

Related

HTML with an input tag isn't found by getElementsByTagName [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 6 years ago.
I wrote the following HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Test</title>
<script type = "text/javascript" src =
"../js/test.js"></script>
</head>
<body>
<p><input type = "button" value = "Click";></input></p>
</body>
</html>
and the corresponding JavaScript file test.js
var inputs = document.getElementsByTagName("input");
console.log(inputs.length);
and the value shown is 0. Can anyone explain?
You are trying to get the element before it's loading to DOM, to execute after elements are loaded move the script tag after the elements or add it within the onload event handler.
window.onload = function(){
var inputs = document.getElementsByTagName("input");
console.log(inputs.length);
}

Can't display board whereas the ID is same when I use chessboard.js

I want to display chess from chessboardjs.com. But I can't whereas I follow documentation. And whereas the ID is same.
<html>
<head>
<!--
UTF-8 (U from Universal Character Set + Transformation Format—8-bit[1]) is a character encoding capable of encoding all possible characters
-->
<meta charset="UTF-8">
<link rel="stylesheet" href="css/chessboard-0.2.0.css"/>
<script type="text/javascript" src="js/chessboard-0.2.0.js" > </script>
<script type="text/javascript">
var board1 = new ChessBoard('board1', 'start');
</script>
</head>
<body>
<div id="board1" style="width: 400px"></div>
</body>
The id is same. It is 'board1'. I follow the rules from the documentation...
link
But, I get error. The error is chessboard error 1002: element with id "board1" does not exist in the DOM.
Then, I read documentation about error 1002. It says..
ChessBoard could not find your element with document.getElementById. Please note that if you pass a string as the first argument to the ChessBoard() constructor it should be the value of a DOM id, not a CSS selector (ie: "board", not "#board").
link
You don't need the entire jQuery library to get this to work, though you may find it helpful for other things. If you don't foresee using jQuery for anything else all you need is setTimeout
setTimeout(function() {
var board1 = new ChessBoard('board1', 'start');
}, 0);
I accidentally discovered this trick 6 years ago and posted a question that got this informative answer. He did point out that it may not work in IE though perhaps that has changed in the meantime.
You need jquery to make this work.
<html>
<head>
<!--
UTF-8 (U from Universal Character Set + Transformation Format—8-bit[1]) is a character encoding capable of encoding all possible characters
-->
<meta charset="UTF-8">
<link rel="stylesheet" href="css/chessboard-0.3.0.css"/>
<script type="text/javascript" src="js/chessboard-0.3.0.js" > </script>
<script src="https://code.jquery.com/jquery-1.10.1.js"></script>
</head>
<body >
<div id="board1" style="width: 400px"></div>
</body>
<script type="text/javascript">
var init = function() {
//--- start example JS ---
var board = new ChessBoard('board1');
//--- end example JS ---
}; // end init()
$(document).ready(init);
</script>
</html>

Why isn't the following javascript code working? (Crafty.js used)

I am a newbie, in crafty as well as js, so pardon me if I might have made very silly errors in the following program.
What is wrong with the following code? The following code is supposed to create 5*5 matrix where each block would be a 60 pixel high and wide iceblock as stored in iceblock.jpg.
window.onload=function()
{
Crafty.init(500,500);
Crafty.canvas();
Crafty.sprite(60,"iceblock.jpg",{block : [0,0]});
Crafty.c("iceblock",function(){
init: function(){
this.addComponent("2D, Canvas, Mouse, block");
this.w = 60;
this.h = 60;
}
});
};
for(var i=0;i<5;i++)
{
for(var j=0;j<5;j++)
{
Crafty.e("iceblock").attr({x: i*60,y: j*60})
}
}
The corresponding HTML code is:-
<!DOCTYPE html>
<head>
<script type="text/javascript" src="crafty.js"></script>
<script type="text/javascript" src="assignment.js"></script>
<title>My Crafty Game</title>
</head>
<body>
</body>
</html>
When I open the HTML page, the complete output page is blank.
This is the link to the image.
http://postimage.org/image/ivqfhmjt9/
PS:- Is there a less annoying way to indent our code instead of putting 4 spaces infront of each line? Very time consuming and tedious.
For reference, see this thread https://groups.google.com/forum/?fromgroups#!topic/craftyjs/OkG5rFb3tqo
Or the code here http://jsfiddle.net/cYxeZ/

getElementsByTagName().length returns zero

I am trying to do a simple thing such as:
var elements = document.getElementsByTagName("input");
console.log(elements);
console.log(elements.length);
The console.log(elements) shows the NodeList containing 28 input elements, but the elements.length is always 0.
I've also seen this getElementsByTagName("div").length returns zero for any webpage however I didn't understand what exactly is the reason for it happening and how to fix it. I've also noticed that this happens on both Firefox, IE, Chrome.
Anyone could help me out?
NodeList is a live collection and non-deferred scripts execute immediately (see script defer).
Try this and you will get an idea of what happens:
<html>
<head>
<title></title>
<style></style>
<script type="text/javascript">
var elements = document.getElementsByTagName("div");
alert(elements.length);
</script>
</head>
<body>
<div>1</div>
<script type="text/javascript">
//var elements = document.getElementsByTagName("div");
alert(elements.length);
</script>
</body>
</html>
This happens because of the asynchronous behaviour of JS. You're trying to display the element's value before it is being rendered.
In order to avoid it, you could add the "async" attribute to your tag, as in the following example:
<script type="text/javascript" src="myTag.js" async></script>
your script should have the attribute "deter" to detect the tags

Issues with most basic e4x test

When I load a page containing e4x in FF 3.5, I get no inkling that e4x even exists in the browser's JS implementation. Notes below, but here's my HTML :
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>e4x test</title>
<script type="text/javascript" src="lib/dojo/dojo/dojo.js">
</script>
<script type="text/javascript;e4x=1">
function hello() {
var x = new XML();
x = <foo></foo>
dojo.byId("container").innerHTML = "Print me!" + x.toXMLString();
}
</script>
<script type="text/javascript">
dojo.addOnLoad(hello);
</script>
</head>
<body>
<div id="container">
</div>
</body>
</html>
When I inspect in firebug, it says x doesn't have a toString() method, and my IDE (aptana) thinks that XML is not an object type. Does anyone have any idea what I'm doing wrong?
I'm guessing that it was working all along, but your browser doesn't recognize a "foo" tag and because it does not know how to render it, it ignores it. By putting something inside of your foo tag you would get content out.
BTW: The new XML() statement is entirely unnecessary. You can just do this:
var x = <foo>bar</foo>;
That will create a new XML object for you. Saying new XML() is like saying new String(). You can do it, but it is just a waste of space.
It turns out that I need more in the XML for it to print anything out. bar works, for example. I'm not sure why, but that is what fixed it!

Categories