Can't access DOM element - javascript

I wrote a web application with a body onload event. I know this isn't optimal so I want to use DOMContentLoaded to trigger my init event.
I have a strange problem, I can't access my DOM element and I don't know why :/.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="main.js"></script>
</head>
<body>
<div id="test">Hello World</div>
</body>
</html>
JS:
// add event listener
document.addEventListener('DOMContentLoaded', init, false);
function init () {
// pop up
alert(document.getElementById(test).innerHTML);
}
Does somebody see the problem?

You are passing the undefined variable test to the getElementById() function, instead of the string value 'test'.
So
document.getElementById(test); // Incorrect - as an undefined varible
Should in fact be
document.getElementById('test') // Correct - as a string value
Or
var element_id = 'test';
document.getElementById(element_id) // Correct - as a defined variable

Add double quotes around test i.e. "test"
document.addEventListener('DOMContentLoaded', init, false);
function init () {
// pop up
alert(document.getElementById("test").innerHTML);
}

If your init function is executed, then you might add quote arroud your id :
document.getElementById(test)
becomes
document.getElementById('test')

Related

click(jquery) executes the function as soon as script is loaded and doesn't responds to clicks

I was trying to execute a function using .click (jquery 3.4.1) when a button is pressed but the function executes as soon as the page loads. And after some trying I thought there might be some piece of code that is making it behave this way so I created new files with basic elements and tried using it but it still didn't work. I thought I might be doing something wrong and so I checked a tutorial but it didn't help because I was doing the same thing.
I tried .on('click', function) too but the result was same.
The .html file
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1 style="text-align: center;">Some Text</h1>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="test.js"></script>
</body>
</html>
The .js file
$('h1').click(console.log('Clicked'))
Any idea why it isn't working?
You are attaching a click event listener to the h1
$('h1').click(console.log('Clicked'))
What is does is it executes the console and what it returns is assigned to the event listener. So that is why it is not working. You basically just did the following because console does not return anything.
$('h1').click(undefined)
so you have to assign it a function
$('h1').click(function () { console.log('Clicked') })
// Your original way written out to see what is happening
// $('h1').click(console.log('Clicked')) // code below is same thing as this line
var cl = console.log("Clicked Original Way") // will log message
console.log('cl is:', cl) // cl is: undefined
$('h1').click(cl) // aka $('h1').click(undefined)
// solution 1
$('h1').click(function() {
console.log('Clicked')
})
// solution 2
function myClickFunction() {
console.log('Clicked w/ function')
}
$('h1').click(myClickFunction)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 style="text-align: center;">Some Text</h1>
Since the argument you're passing in is not a callable function, jQuery is unable to call it when the click actually happens. Try something like this:
$(document).ready(function() {
$('h1').on('click', function(e) {
console.log('clicked');
});
});
click expects a function
$('h1').click(function() {
console.log('Clicked');
});
The way you are doing it, is to output 'Clicked' and have a undefined handler "sent" to click().
Check out the documentation here

Getting entire HTML in JavaScript

I'm trying to get the entire HTML of a page, but it seems that the text stops after </head>. The following code is essentially how I tested this. What am I doing incorrectly here?
<html>
<head>
<script>
document.onload = showHTML();
function showHTML() {
html = document.documentElement.innerHTML;
alert(html);
}
</script>
</head>
<body>
<p> This is absolutely useless text. </p>
</body>
</html>
Okay here is a complete working answer... after checking already posted answer I realized it didn't work for multiple reasons..
First you need to put a function in the onload event. The onload event is written without uppercases.
Also! you need to put the event on the window object as such:
window.onload = showHTML;
Here is a fiddle. Notice on the left that it isn't wrapped inside onload. It's unwrapped in head like your code should be.
http://jsfiddle.net/4zsGH/2/
You should have something like this:
<html>
<head>
<script>
window.onload = showHTML;
function showHTML() {
var html = document.documentElement.outerHTML;
alert(html);
}
</script>
</head>
<body>
<p> This is absolutely useless text. </p>
</body>
</html>
Take off the parenthesis from document.onLoad = showHTML();
What's happening is showHTML() is being called right away, before the rest of the document is being loaded. Taking off the parenthesis means the function is being set to the onLoad callback.
Try:
<html>
<head>
<script>
document.onload = showHTML;
function showHTML() {
var html = document.documentElement.outerHTML;
alert(html);
}
</script>
</head>
<body>
<p> This is absolutely useless text. </p>
</body>
</html>
When you wrote document.onLoad = showHTML(); you didn't assign the reference to showHTML function to document.onLoad but you assigned the value returned by that function i.e. undefined (because you called it). I also changed innerHTML to outerHTML.
Also document.onload shouldn't be written in camel case.
Writing var html = … isn't essential but it wouldn't run in strict mode. Without it you create a html property on global object window implicitly.
I think this is what you are looking for:
document.onLoad = showHTML();
function showHTML() {
var html = document.documentElement.innerHTML;
alert(html);
}
http://jsfiddle.net/skhan/4zsGH/

JQuery $('#id") does not work

I'm a noob in JQuery, trying my hands on the basic functionality of it
I have a html, like below.
<html>
<head>
<script type="text/javascript" charset="utf-8" src="js/jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="js/start.js"></script>
<script>
$(mainFunction());
$('#label1').prop('innerHTML', "test");
</script>
<title></title>
</head>
<body>
<label id="label1"></label>
</body>
</html>
From start.js, i'm trying to manipulate the elements in this html file like below.
function start(name){
this.iam = name;
this.getName = function(user){
return this.iam;
}
}
function mainFunction(){
var label = $('#label1');
var oStart = new start("test");
label.prop("innerHTML" ,oStart.getName("test"));
}
When I try to lookup whats in the 'label' in the above code, i get [] printed on the console. What am I doing wrong here?
$(mainFunction()); is your issue. Instead provide function reference to document.ready.
Like this:
$(mainFunction);
While doing $(mainFunction()); you are invoking the function mainFunction while setting up the handler, which means it gets executed too early before the DOM tree has been constructed.
Or in order to avoid confusion you could do:
$(function(){
mainFunction();
});
Also remember that this issue will not happen if you move your script just before the end of the body tag. You do not have to listen to document ready handler. Plus as a shorthand you could just do label.html(oStart.getName("test"));
You need to wait for the DOM to be ready before using jQuery.
This is done this way:
$(document).ready(function() {
// All your code touching the DOM in here
});
Also note that this line: $(mainFunction()); uses the return value of mainFunction, it does not trigger it when DOM is ready.

Using document.getElementById() inside object, works in JSFiddle, TypeError in actual. Why?

I have a code that works in JSFiddle but doesn't work when I save the HTML+JS locally and test it locally. I can't figure out what's wrong with the code. Here is my JSFiddle
http://jsfiddle.net/LLUAB/
And here is the actual code, not very long
<!doctype html>
<html>
<head>
<script type="text/javascript" language="Javascript">
function Composer(foobox) {
this.foobox = document.getElementById(foobox);
this.foobox.onkeydown = function(){window.alert("hello")};
}
var myComposer = new Composer("foo");
</script>
</head>
<body>
<textarea id="foo"></textarea>
</body>
</html>
Because in JSFiddle your script is placed inside window.onLoad event handler by default. While in your case getElementById() method is unable to find not yet loaded element.
Put all your script right before closing </body> tag and it will work:
<script type="text/javascript">
// ...
</script>
</body>
It works in Fiddle because of onLoad option specified here. The problem is that when new Composer line is fired, there's no such element in the DOM yet. Wrap this line in DOMReady handler - or move its invokation to the end of <body> element.
It's because your dom is not ready yet
function Composer(foobox) {
this.foobox = document.getElementById(foobox);
alert(this.foobox); --Prints null
this.foobox.onkeydown = function(){window.alert("hello")};
}
Working code here. http://jsfiddle.net/LLUAB/1/

javascript function name cannot set as click?

Below is my code and it doesn't work. After I rename the "click()" to "click1()" it works, why?
<html>
<head>
<title></title>
<script type="text/javascript">
function click() {
document.getElementById("content").innerHTML = "abc";
}
</script>
</head>
<body>
<button onclick="click()">try it</button><br />
<div id="content"></div>
</body>
</html>
The string values of "onfoo" handler attributes are interpreted as the bodies of handler functions. In other words, it's as if the string value of the attribute is passed to new Function("event", str) with the result being the handler function used.
Additionally, the lexical scope of the function is established as follows, taken from the HTML5 spec (which I consult only in its capacity of a comprehensive description of browser behavior):
Lexical Environment Scope
* Let Scope be the result of NewObjectEnvironment(the element's Document, the global environment).
* If the element has a form owner, let Scope be the result of NewObjectEnvironment(the element's form owner, Scope).
* Let Scope be the result of NewObjectEnvironment(the element's object, Scope).
Thus it's as if there are up to two nested with blocks implicitly wrapped around the code. Thus in this case the effect is that of calling this:
var handler = new Function("event", "with (this) { click(); }");
Because there's a "click" method on the DOM element corresponding to the <button>, that function is what's called by the handler, not the global one established by the script tag. If the "onclick" attribute is set to "window.click();" then the page works properly.
There's already a function called click, responsible for calling the event handler. By declaring another, you override the first, so the event doesn't work anymore.
click() is the inbuilt of javascript's button object.
click() a reserved name for a method used in HTML5 http://www.w3.org/TR/html5/webappapis.html
click is predefined event. You should not use predefined events.
You should perhaps consider using jQuery to refactor your code:
<html>
<head>
<title></title>
</head>
<body>
<button id="button1">try it</button><br />
<div id="content"></div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#button1").click(function() {
$("#content").html("abc");
});
});
</script>
</body>
</html>

Categories

Resources