getElementById cannot access the loaded DOM - javascript

HTML
<div>
<label>City:<input id="aqi-city-input" class="122" type="text" ></label><br>
<label>Point:<input id="aqi-value-input" type="text"></label><br>
<button id="add-btn">OK</button>
</div>
JavaScript
var CityName = document.getElementById('aqi-city-input');
var CityMore = document.getElementsByClassName('122');
var Quality = document.getElementById('aqi-value-input');
var Button = document.getElementById('add-btn');
console.log(document.getElementById('aqi-city-input')); //null
console.log(CityName); //null
console.log(CityMore); //html object
console.log(Quality); //null
console.log(Button); //null
There return null except the getElementsByClassName, do I have something wrong ?

You have to include your JavaScript after the HTML document like the following. If you are using a JavaScript file you have to include this after the HTML document too.
<div>
<label>City:<input id="aqi-city-input" class="122" type="text" ></label><br>
<label>Point:<input id="aqi-value-input" type="text"></label><br>
<button id="add-btn">OK</button>
</div>
<script src="path/to/your/script.js"></script>
<script>
var CityName = document.getElementById('aqi-city-input');
var CityMore = document.getElementsByClassName('122');
var Quality = document.getElementById('aqi-value-input');
var Button = document.getElementById('add-btn');
console.log(document.getElementById('aqi-city-input'));
console.log(CityName);
console.log(CityMore);
console.log(Quality);
console.log(Button);
</script>
You can also use the JavaScript before your HTML document, but in this case you have to wrap your code in a event listener DOMContentLoaded so the JavaScript executes if the HTML content is loaded (and JavaScript can see the HTML elements).
In case of a JavaScript file you should wrap your code into the event listener.
<script src="path/to/your/script.js"></script> <!-- content is wrapped in event listener -->
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var CityName = document.getElementById('aqi-city-input');
var CityMore = document.getElementsByClassName('122');
var Quality = document.getElementById('aqi-value-input');
var Button = document.getElementById('add-btn');
console.log(document.getElementById('aqi-city-input'));
console.log(CityName);
console.log(CityMore);
console.log(Quality);
console.log(Button);
});
</script>
<div>
<label>City:<input id="aqi-city-input" class="122" type="text" ></label><br>
<label>Point:<input id="aqi-value-input" type="text"></label><br>
<button id="add-btn">OK</button>
</div>

Move your javascript code below your HTML.Or execute it after the page has finished loading.In JQuery you can do like below:
<script>
$(document).ready(function() {
//... your code ...//
});
</script>

Related

How to change HTML content multiple times with one button using JS (no JQuery)?

I have the following piece of code, which changes one line of text in a click of a button:
<!DOCTYPE html>
<html>
<body>
<h1>Change content exercise</h1>
<p id="demo">Watch this HTML content changes..</p>
<button type="button"
onclick="document.getElementById('demo').innerHTML = 'This is JavaScript!'">
Click Me!</button>
</body>
</html>
This is quite easy since there is no script, no function needed to handle the button. Now, I want this same button to change back to the first content when I click it again. I assume that now I need to have a function, but not sure how to write it. An ideas?
You don't have to use a function. You could do it with a ternary operator ? and :, or you could even just write an if else statement all on one line.
<h1>Change content exercise</h1>
<p id="demo">Watch this HTML content changes..</p>
<button type="button"
onclick="document.getElementById('demo').innerHTML === 'This is JavaScript!' ? document.getElementById('demo').innerHTML = 'Watch this HTML content changes..' : document.getElementById('demo').innerHTML = 'This is JavaScript!';">
Click Me!</button>
However, that is a lot of code to cram into one line and it would be much cleaner in a separate function, as such.
function changeText() {
var demo = document.getElementById('demo');
if (demo.innerHTML === 'This is JavaScript!') {
demo.innerHTML = 'Watch this HTML content changes..';
} else {
demo.innerHTML = 'This is JavaScript!';
}
}
<h1>Change content exercise</h1>
<p id="demo">Watch this HTML content changes..</p>
<button type="button" onclick="changeText()">Click Me!</button>
Well. Although the way you are trying is not the best practice.... But the following way will give you some hope. try to do more research.
function myFunction() {
var x=document.getElementById("demo").innerHTML;
if(x=="A Paragraph."){
document.getElementById("demo").innerHTML="Back Again";}
if(x=="Back Again")
document.getElementById("demo").innerHTML="A Paragraph.";
}
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
More simply, this function works:
<h1>Change content exercise</h1>
<p id="demo">Watch this HTML content changes..</p>
<button type="button" onclick="changeText()">Click Me!</button>
Javascript:
function changeText() {
e = document.getElementById('demo');
e.innerHTML = e.innerHTML == "Watch this HTML content changes.." ? "This is JavaScript!" : "Watch this HTML content changes..";
}
You can see it working at this JS Fiddle: http://jsfiddle.net/0yLb4a3j/
You can have something like a toggle function:
<script type="text/javascript">
function toggleContent() {
var message1 = "This is JavaScript!";
var message2 = "Watch this HTML content changes..";
var element = document.getElementById('demo');
if (element.innerHTML===message1)
element.innerHTML = message2;
else
element.innerHTML = message1;
return false;
}
</script>
You get it called by setting onclick="toggleContent();" on the button.
You could use an IIFE, an array, an incremented counter, and a modulo operator to achieve this.
document.getElementById('button').onclick = (function(){
var demo = document.getElementById('demo');
var text = [demo.textContent,'This is JavaScript!'];
var count = 0;
return function() {
demo.textContent = text[++count % 2];
}
})();
<p id="demo">Watch this HTML content changes..</p>
<button type="button" id="button">Click Me!</button>
var btn = document.getElementById("<btn_id>");
var previous = "";
btn.addEventListener("click", clickHandler);
function clickHandler() {
var demo = document.getElementById("demo");
if (!previous) {
previous = demo.innerHTML;
} else {
demo.innerHTML = "This is JS";
btn.removeEventListener("click", clickHandler);
}
}
first of all , you ll need to do the code in a seperate script, in brief , append the intial text to the div then wheck button clicked, change it to second text, and according to your question you ll need a second button who will change the div text to the intial text , logically that ll give something like tht :
<script>
window.onload = function(){
document.getElementById('demo').innerHTML = 'Watch this HTML content changes..'
}
document.getElementById('button1').Onclick = function(){
document.getElementById('demo').innerHTML = 'This is JavaScript!'
};
document.getElementById('button1').Onclick = function(){
document.getElementById('demo').innerHTML = ''Watch this HTML content changes..'
};
</script>

calling Jquery Function not working

I'm currently following a tutorial and the person in the tutorial is coding css, html, and jquery all in one file. I split them up into seperate files. My problem is the code in the tutorial works when calling a function and mine does not, even though the code is exactly the same. Here is some of my code
//Jquery File
function username(){
$("#container").html("<span class = 'bot'>Chatbot: </span>Hello, what is your name?");
}
$(function(){
username();
$("#textbox").keypress(function(event){
........
HTML File
<div id = "container">
</div>
<div id = "controls">
.....
Tutorial Code
<script type="text/javascript">
function username(){
$("#container").html("<span class = 'bot'>Chatbot: </span>Hello, what is your name?");
}
$(function(){
username();
$("#textbox").keypress(function(event){
.......
It's exactly the same but for some reason my code does not work, I tested out both. And i know I'm linking to the correct jQuery files because my other function work fine no problem.
Full HTMl
JQuery Chatbot Tutorial
jQuery Chatbot v. 1.0 Tutorial
<div id = "container">
</div>
<div id = "controls">
<textarea id = "textbox" placeholder = "Enter your message here..."></textarea>
<button id = "send">Send</button>
<br>
<input checked type = "checkbox" id = "enter"/>
<label>Send on enter</label>
</div>
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="chatbot.js"></script>
</body>
Full JQuery File
function username(){
$("#container").html("<span class = 'bot'>Chatbot: </span>Hello, what is your name?");
}
$(function(){
username();
$("#textbox").keypress(function(event){
if ( event.which == 13){
if ( $("#enter").prop("checked") ){
$("#send").click();
event.preventDefault();
}
}
});
});
$("#send").click(function(){
var username = "<span class ='username' = >You: </span>";
var newMessage = $("#textbox").val();
$("#textbox").val("");
var prevState = $("#container").html();
if (prevState.length > 3){
prevState = prevState + "<br>";
}
$("#container").html(prevState + username + newMessage);
$("#container").scrollTop($("#container").prop("scrollHeight"));
});
You might have error in the code before the call. Try:
$(function(){
alert('Debug me 2');
username();
alert('Debug me 2');
...
and see what happens.

Issue trying to get website to work - possible issue with my html code?

SO I have code that I'm trying to implement from my jsfiddle into an actual working website/mini-app. I've registered the domain name and procured the hosting via siteground, and I've even uploaded the files via ftp so I'm almost there...
But I'm thinking there's something wrong with my HTML code or JS code or how I implemented my JS code into my HTML code, because all of the HTML and CSS elements are present, but the javascript functionality is absent.
Here is my fiddle:
jsfiddle
^^ Click on start to see the display in action (which doesn't work in the actual website, which leads me to believe there's an issue with my JS file - whether it be code-related or whether that's because I integrated the file incorrectly) (or maybe even uploaded to the server incorrectly, perhaps?)...
And here is the actual site:
http://www.abveaspirations.com/index.html
And here's my HTML code uploaded to the server via FTP:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id='frame'>
<div id='display'>
<h1 id='output'></h1>
</div>
</div>
<div class="spacer">
</div>
<div id="main"> <!-- 11main -->
<h1 id='consoleTitle'>Control Board</h1>
<h5 id='consoleSub'><i>Double-click on an entry to remove. And add entries to your heart's desire...</i></h5>
<div id="controlbox"> <!-- ##controlbox -->
<div id="controlpanel"></div>
<div class="spacer"></div>
<div id="formula"> <!--formula -->
<form id="frm" method="post">
<input id="txt" type="text" placeholder="Insert your own entry here..." name="text">
<input id='submitBtn' type="submit" value="Start">
<input id='stop' type="button" value="Stop">
<select id="load1">
<option id='pre0' value="Preset 0">Preset 0</option>
<option id='pre1' value="Preset 1">Preset 1</option>
<option id='pre2' value="Preset 2">Preset 2</option>
</select>
<!-- These are for buttons as opposed to OPTION...
<input id="load" type="button" value="Preset 1">
<input id="load2" type="button" value="Preset 2"-->
</form>
</div> <!-- formula -->
</div> <!-- ##controlbox -->
</div> <!-- 11main -->
</body>
And my JS code, also uploaded to server via FTP (I didn't include the accompanying CSS file, but if that would help, I can provide ):
$(document).ready(function () {
var txtBox = $('#txt');
var frm = $('#frm');
var output = $('#output');
var subBtn = $('#submitBtn');
var stopBtn = $('#stop');
var loadBtn = $('#load');
var loadBtn2 = $('#load2');
var loadBtnA = $('#load1');
var pre0 = $('#pre0');
var pre1 = $('#pre1');
var pre2 = $('#pre2');
var txt = $('#display');
var preset1 = ["1", "2", "3"];
var preset2 = ["a", "b", "c"];
var container = ["What we do in life echoes in all eternity.", "Find your purpose and give it life.", "When you work your hardest, the world opens up to you."];
var console = $('#controlpanel');
var oldHandle;
function loadPreset0() {
container = [];
console.empty();
container = ["What we do in life echoes in all eternity.", "Find your purpose and give it life.", "When you work your hardest, the world opens up to you."];
updateConsole();
};
function loadPreset1() {
container = [];
console.empty();
container = preset1;
updateConsole();
};
function loadPreset2() {
container = [];
console.empty();
container = preset2;
updateConsole();
};
$(pre0).data('onselect', function() {
loadPreset0();
});
$(pre1).data('onselect', function() {
loadPreset1();
});
$(pre2).data('onselect', function() {
loadPreset2();
});
$(document).on('change', 'select', function(e) {
var selected = $(this).find('option:selected'),
handler = selected.data('onselect');
if ( typeof handler == 'function' ) {
handler.call(selected, e);
}
});
function updateConsole() {
for (var z = 0; z < container.length; z++) {
var resultC = container[z];
var $initialEntry = $('<p>' + '- ' + resultC + '</p>');
console.append($initialEntry);
};
};
updateConsole();
frm.submit(function (event) {
event.preventDefault();
if (txtBox.val() != '') {
var result = txtBox.val();
container.push(result); //1.
var resultB = container[container.length-1];
var $entry = $('<p>' + '- ' + resultB + '</p>');
console.append($entry); //2.
}
var options = {
duration: 5000,
rearrangeDuration: 1000,
effect: 'random',
centered: true
};
stopTextualizer();
txt.textualizer(container, options);
txt.textualizer('start');
txtBox.val('');
});
$("#controlbox").on('dblclick', 'p', function() {
var $entry = $(this);
container.splice($entry.index(), 1);
$entry.remove();
});
function stopTextualizer(){
txt.textualizer('stop');
txt.textualizer('destroy');
}
$(stopBtn).click(function() {
stopTextualizer();
});
});
Any help would be appreciated. I guess I'm just not sure what to do after uploading the html file to the server via ftp. Or maybe I did that correctly and there's something wrong with my code that I'm overlooking. Basically I'm lost. So help please!
You forgot to load jQuery. Make sure that you use <script src="../path-to-jquery/jquery.js"></script> before you load your script.js script.
Also, I noticed that you're loading your scripts in the head tag. This is bad practice, load them right before </body>.
I believe your site is missing jQuery. Add this to the top of your code to hotlink to google's jQuery.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

adding html into a div without id

i'm trying to add some html code with javascript and jQuery into a div without an id, but with a class
i'm trying to have it done like this, but without success...
flie.js :
$(".myClassName").ready(function(){
$(this).innerHTML = "<img src=\"http://mywebsite.com/img.png\" /> <span>some text</span>";
});
i'm loading the .js file with this html code
.html file :
<div class="myClassName">
</div>
<script>
(function()
{
if (window['ImportFlag'] == undefined || window['ImportFlag'] == void 0) {
var myScript = document.createElement('script');
myScript.type = 'text/javascript';
myScript.src = 'file.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(myScript, s);}
window['ImportFlag'] = 1;
})();
</script>
$(document).ready(function(){
$(".myClassName").html("<img src=\"http://mywebsite.com/img.png\" /> <span>some text</span>");
});
You may try like this
<div class="myClassName">
</div>
<script type="text/javascript" src="file.js">
</script>​
file.js
$(document).ready(function(){
$('.myClassName').html("<img src=\"http://mywebsite.com/img.png\" /> <span>some text</span>");
});​
You should firs ensure that jQuery is loaded BEFORE loading file.js. Then you should use jQuery's functions to set the div inner HTML.
This is a minimalist example :
<html>
<head></head>
<body>
<div class="myClassName">
</div>
<script type="text/javascript" src="/js/jquery-1.7.2.min.js"></script>
<script>
(function()
{
if (window['ImportFlag'] == undefined || window['ImportFlag'] == void 0) {
var myScript = document.createElement('script');
myScript.type = 'text/javascript';
myScript.src = 'file.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(myScript, s);}
window['ImportFlag'] = 1;
})();
</script>
</body>
</html>
Then, file.js :
$(document).ready(function(){
$(".myClassName").html("... <span>some text</span>");
});
The jQuery ready() function should be called on the document object, not on an element. It evokes a DOM-ready handler, and can be called using the following syntax (from the official documentation):
$(document).ready(handler)
$().ready(handler) (this is not recommended)
$(handler)
Matei Mihai and muthu's answers here show you how this works for your example.

Using prototype in javascript

I have defined a couple of functions inside my javascript which work perfectly, but when I put it inside a prototype it just doesn't seem to work.
wall.html:
<script type="text/javascript" src="Jquery/jquery-1.4.4.js"> </script>
<script type="text/javascript" src="src/CommentManager.js"> </script>
<script type="text/javascript" src="src/Reply.js"> </script>
<script type="text/javascript" src="src/Comment.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
CommentManager();
$("form#newMessage").submit(function(){
var message = $("input#newMessageTxt").val();
var newComment = new Comment(message);
});
});
</script>
</head>
<body>
<div class="message">
<form id="newMessage">>
<input type="text" id="newMessageTxt" height="200px" value="Write a message" onfocus="if(this.value==this.defaultValue) this.value='';" onblur="if(this.value=='') this.value=this.defaultValue;" />
<input type="submit" value="Submit" ></button>
</form>
</div>
</body>
but the weird part is when I run the debugging tool in googlechrome, the $("form#newMessage").submit doesn't call at all. So Comment(message) is never created (which is where I have set up the prototype functions)
Comment.js:
function Comment(message){
var self = this;
var message = message;
var comment = document.createElement("li");
comment.id = "comment";
comment.textContent = message;
//empty reply field
var replyField = document.createElement("ul");
replyField.id = "replyField";
//create the appropriate buttons
createButtons(comment);
//append the replyField
comment.appendChild(replyField);
//insert into wall
addComment(comment);
//effect after insertion
Effect(comment);
$(comment).mouseleave(function() {mouseOut(comment);});
$(comment).mouseenter(function() {mouseOver(comment);});
return comment;
}
Comment.prototype={
deleteComment : function (comment){
$(comment).fadeOut();
setTimeout(function() {comment.parentNode.removeChild(comment);},500);
},
//there are more methods here
}
Commentmanager.js:
function CommentManager(){
var owner = null;
var wall = document.createElement("ul");
wall.id = "wall";
document.body.appendChild(wall);
return wall;
}
function addComment(comment){
var wall = document.getElementById("wall");
wall.appendChild(comment);
}
Where is createButtons defined? (in Comment.js)?
Also, you you titled that last file as Commentmanager.js, but wall.html has CommentManager.js (notice the capital M in wall.js). I'm assuming that's a typo here in the SO question, but make sure that your filenames on the server match the html script tags.

Categories

Resources