This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 3 years ago.
I'm trying to write simple web app in VSCode. I have little misunderstanding. May be its really simple thing, but i don't know why it doesn't work normally like in examples which i saw.
i have js file (script.js)
function getHistory(){
return document.getElementById("history-value").innerText;
}
alert( getHistory());
and my index.html where i'm using div's tags
<div class="result">
<div class="history">
<p id="history-value">55555</p>
</div>
<div class="output">
<p id="output-value" class="output-value">7777777</p>
</div>
</div>
in beginning of course referense to js
<head>
<title>Calculator</title>
<meta charset="utf-8" >
<link rel="stylesheet" href="style.css">
<script src="script.js">
</script>
</head>
But allert are not working. I can't see nothing. If i use
console.log (document.getElementById("history-value").innerText );
it shows null in console window.
Please explain me what's wrong with it?
1) As Java script is loaded before html page so you have to add script tage at bottom of the page in your case as you are taking value of history-value element which you have added after script tag so when script tag is loaded there is no element with id history-value so you will get null. So you have to add this script after this element
index.html
<head>
<title>Calculator</title>
<meta charset="utf-8" >
<link rel="stylesheet" href="style.css">
</head>
<div class="result">
<div class="history">
<p id="history-value">55555</p>
</div>
<div class="output">
<p id="output-value" class="output-value">7777777</p>
</div>
</div>
<script src="script.js"></script>
script.js
function getHistory(){
return document.getElementById("history-value").innerText;
}
alert( getHistory());
The problem is that your <script> tag appears in the <head> section of your document, and when the script loads, the rest of your HTML has not yet been loaded by the browser, so the <p id="history-value"> tag effectively does not yet exist as far as the browser is concerned.
In this case, you should put your <script> tag just before the </body> tag, or at the very least after the <p id="history-value"> tag, so that <p> tag appears before the Javascript attempts to read it.
It looks like the script runs when there is no history-value element.
Are you sure you are running the code after document has been loaded?
Your code work in the following snippet (but I guess is due to the fact that javscript is loaded at the end of the document).
But to make sure you can place into a
document.addEventListener( 'DOMContentLoaded', function( event ) {
// your code here
})
function getHistory(){
return document.getElementById("history-value").innerText;
}
document.addEventListener( 'DOMContentLoaded', function( event ) {
alert(getHistory());
});
<div class="result">
<div class="history">
<p id="history-value">55555</p>
</div>
<div class="output">
<p id="output-value" class="output-value">7777777</p>
</div>
</div>
Related
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 have this simple HTML file:
<!DOCTYPE html>
<html>
<head>
<script src='test.js'></script>
</head>
<body>
<p>I am a paragraph tag</p>
<h1 >I am an h1 tag</h1>
<div id="id"> I am a div tag</div>
</body>
And this simple script (test.js):
y=document.getElementById("id");
y.style.color="green";
Why on earth is "y" null? The error I'm getting is
TypeError: y is null
I'm sure this is a simple syntax thing that I'm missing, but I can't for the life of me figure it out! Help!
Post Script: Both the html file and the test.js file are in the same folder.
you have to place the script at the end of the document when all the elements are created:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>I am a paragraph tag</p>
<h1 >I am an h1 tag</h1>
<div id="id"> I am a div tag</div>
</body>
<script src='test.js'></script>
You can wrap the content on your script using $(document).ready if you are using jQuery or window.onload if using plain javascript.
problem is, that the website is loading like for about 20 second or longer (user-problems preprogrammed)
my solution was to load a pre-site where the user sees a loading screen.
i did this with this html-site but i want to do the same in php.
the test-page is http://kater.selfhost.me/test/
Source Code:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<script type="text/javascript">
window.onload = function() {
document.getElementById("siteLoader").style.display = "none";
document.getElementById("container").style.display = "block";
}
</script>
</head>
<body>
<div id="container" style="display:none">
<div id="body">
<iframe src="http://kater.selfhost.me/stats/skins.php" frameborder="0" height="2000px" width="1024px"></iframe>
</div>
</div>
<div id='siteLoader'>
<div id='siteDetailLoader'>
<img src='ajax_loader.gif' border='0'>
Please wait while the page loads...<br /> <br />
</div>
</div>
</body>
</html>
i tried some workarounds, but after searching & testing for about three hours i give up...
thanks in advance for any help provided! :-D
Adding what I alredy said at your question commentary, I made a code loading this content via AJAX:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
//Load content
loadAjaxContent();
});
function loadAjaxContent()
{
//VERY IMPORTANT: the URL domain MUST HAVE be the same as your request
//that's why I'm not writting the full http://kater.selfhost.me/stats/skins.php
$.ajax({
url: "/stats/skins.php"
}).done(function(data) {
//remove loader
$("#siteLoader").hide();
//put PHP content
$("#ajaxContent").html(data);
});
}
</script>
</head>
<body>
<div id="body">
<div id="ajaxContent" style="width:1024px;"></div>
<div id='siteLoader'>
<div id='siteDetailLoader'>
<img src='ajax_loader.gif' border='0' />
Please wait while the page loads...<br /> <br />
</div>
</div>
This is the most used way to load asynchronous content in the web. But pay attention at this: The http://kater.selfhost.me/stats/skins.php page is made to open as single page in the web, so it has <html> , <head>, <body> , etc.. tags, so..after loading this page into another you'll have two <html>, <body> .. tags in a same page, this is bad, but modern browsers have an awesome common sense and don't bother by this, but you should know that, and be aware.
The actual problem why it isn't loading yet, is this javascript in your content:
<script type="text/javascript"><!--
EXref="";top.document.referrer?EXref=top.document.referrer:EXref=document.referrer;//-->
</script>
I removed that and now works fine. Remember that's a quick fix, I don't know what this JS does.
Why it works in <iframe> and doesn't via AJAX? When you open in <iframe> is like opening in a new browser window..and via AJAX, as I have said, it'll load the page content straight inside your "parent" page.
So, removing this Javascript will work, but awesome further solutions:
If you need to open this page both as content to load (via AJAX), both as single page, you can make two pages.. one for each need.
If you just want to use as content to load, remove <html>, <head>, etc.. tags, and fix Javascript to work inside another page.
I have a simple jquery mobile page:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.2">
<link rel="stylesheet" href="js/jquery.mobile-1.2.0.css" />
<script src="js/jquery-1.8.2.js"></script>
<script src="js/jquery.mobile-1.2.0.js"></script>
</head>
<body>
<div id="MyContainer">
<!-- ##################### Raw Part ##################### -->
<div data-role="page">
<div data-role="header">
<h1> Hello World </h1>
</div>
</div>
</div>
</body>
</html>
when I execute that page it renders fine with a black header and title.
The reason why that page loads correctly is because jquery-mobile placed new attributes where needed in fact the innerHTML of MyContainer after the page loads is:
<!-- ##################### Parsed Part ##################### -->
<div data-role="page" data-url="/jqueryMobile/TC_Page/main2.html" tabindex="0" class="ui-page ui-body-c ui-page-active" style="min-height: 1464px;">
<div data-role="header" class="ui-header ui-bar-a" role="banner">
<h1 class="ui-title" role="heading" aria-level="1">
Hello World
</h1>
</div>
</div>
In other words the Raw Part turn into the Parsed Part .
I will like to know what jquery.mobile function made the conversion from the Raw Part to the Parsed Part!
The functions $.mobile.changePage(), $.mobile.loadPage() enables me to do that For example I could do:
// place response from SomeUrl inside the div MyContainer and convert it from raw to parsed!
$.mobile.loadPage('SomeUrl', { pageContainer: $('#MyContainer') });
// later then get the child child (note second child) of MyContainer and make that the child of MyContainer
The problem now is:
All those functions: loadPage, ChangePage etc make an ajax call. What if I already have the html that I want to inject ( I have it in webBrowser local storage or in a Cookie)! In other words how can I make this work:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.2">
<link rel="stylesheet" href="js/jquery.mobile-1.2.0.css" />
<script src="js/jquery-1.8.2.js"></script>
<script src="js/jquery.mobile-1.2.0.js"></script>
</head>
<body>
<div id="MyContainer">
</div>
<script>
function SomeFunction(){
var someHTML = localStorate.html1; // html1 = raw part = <div data-role="page"><div data-role="header"><h1> Hello World </h1></div></div>
$("#MyContainer").html(someHTML);
// now here I am stuck!!!!!!!!!!!!!!!
// how can I make the content of MyContainer go from the raw part to the Parsed Part!
// I am looking for something like:
$JqueryMobile.ParseHTML($("#MyContainer"));
}
</script>
</body>
</html>
Solution
jQuery Mobile provides numerous functions for widget restyling but only one of them will restyle whole page.
$('#index').trigger('pagecreate');
Where #index should be an id of your page DIV.
There is also on other function that can be used here, but unlike trigger('pagecreat'); this function will style only DIV wit data-role="content" attribute. To test this, jsFiddle example trigger('pagecreate'); should be replaced with trigger('create');
$('#index').trigger('create');
If possible SCRIPT tag should not be used inside a BODY tag, while it will work it can cause additional problems. If you want to find more about this topic and how jQuery Mobile handles dynamically added content take a look at this ARTICLE which is a part of my personal blog.
Example
Working example: jsFiddle
This part of code should interest you:
$('#index').append('<div data-role="footer" data-position="fixed"><h1>Dynamicaly added footer</h1></div> ');
$('#index [data-role="content"]').append('<fieldset data-role="controlgroup"><legend>Choose:</legend><input type="radio" name="radio" id="radio1" value="1" checked="checked" /><label for="radio1">option 1</label></fieldset>');
$('#index').trigger('pagecreate');
This code is used to dynamically append page footer and a radio button to page content.
I have a script in an HTML page of the following:
<script id="scriptid" type="text/html">
<div id="insidedivid">
... html code ...
</div>
</script>
I am able to get the HTMLScriptElement using $("#scriptid") but I am not able to get the underlying div object with the id "insidedivid". Whats the way to do it?
It's not possible; the browser does not treat HTML content inside of <script> tags as part of the DOM. When you retrieve the content of the <script> tag with $('#idhere').html(), you're getting a string result.
To answer Troy's question, he's most likely including templates in the <head> of his document so he can ultimately render content dynamically on the browser-side. However, if that is the case, the OP should use a different MIME type than text/html. You should use an unknown MIME type such as text/templates--using text/html confuses what the purpose of the content is.
I'm guessing the reason you're trying to reach into the <script> tag and grab a div is because you've built smaller sub-templates within the single <script> tag. Those smaller templates should rather be placed into their own <script></script> tags rather than contained in one large <script></script> tag pair.
So, instead of:
<script type="text/template" id="big_template">
<div id="sub_template_1">
<span>hello world 1!</span>
</div>
<div id="sub_template_2">
<span>hello world 2!</span>
</div>
</script>
Do this:
<script type="text/template" id="template_1">
<span>hello world 1!</span>
</script>
<script type="text/template" id="template_2">
<span>hello world 2!</span>
</script>
I think it's perfectly valid to have a div inside a script tag (or at
least useful), if a div makes sense to the TYPE you defined for the
script. For example, John Resig uses a script tag with type "text/
html" in his micro-templating solution:
http://ejohn.org/blog/javascript-micro-templating/
In this instance though (and in reply to the original author) you add
an ID to the SCRIPT tag, and refer to that (I don't see why it
wouldn't work with that facebook type instead of html - but you'd
probably want to test it in a few different browsers ;). For the
example you gave, you can get a reference to the DIV by doing:
<script id="scriptid" type="text/html">
<div id="insidedivid">
... html code ...
</div>
</script>
$(function(){
alert($( $( '#scriptid' ).html() ).text() ); //alerts " ... html code ..."
});
The "trick" is to get the HTML of the script tag and turn in into DOM
elements with jQuery - but remember, because you are passing all the
HTML into the jQUery function then you are immediately selecting ALL
of the top level elements. In this case, there is just one DIV - so
you are just selecting that.
Your HTML is invalid. HTML Validator.
If you want to have HTML you can get just like that, use something like this:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" />
<title></title>
<script type="text/javascript" src="//code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var msg1 = $('message1');
// Execute code here
});
</script>
</head>
<body>
<div id="content">Content</div>
<div id="hidden" style="display: none">
<div id="message1">Message 1</div>
<div id="message2">Message 2</div>
</div>
</body>
</html>
If you are making a templating system, you may want to use AJAX instead.
The following code is a test piece. Normally the href in the Link would point to "http://www.google.com/", but the attr should change it to reference "http://maps.google.com" BUT, the reference is not changing. Can anyone tell me why it is not working? Thanks
<html>
<head>
<script type="text/javascript">
$("a#changeme").attr('href',
'http:\/\/maps.google.com/');
</script>
</head>
<body>
<div class="content">
<p>Link to <a href="http://www.google.com/"
id="changeme">Google</a>
in the content...</p>
</div>
</body>
</html>
jQuery is not loaded.
If it was, you would have to wrap it in a $(document).ready handler.
This can be done without jQuery.
Code:
window.onload = function() {
document.getElementById("changeme").href = 'http://maps.google.com/';
};
The onload handler is not exactely equal to the DOMContentLoaded handler, but it has a better support, and may be preferred here. Alternatively, you can move the <srcipt> block to the end of the <body>, and then use the method without any onload handlers:
<body>
<div class="content">
<p>Link to Google
in the content...</p>
</div>
<script type="text/javascript">
// This code is placed after the element, so the reference does exist now.
// In the head, the same code will throw an error, because the body doesn't
// even exist.
document.getElementById("changeme").href = 'http://maps.google.com/';
</script>
</body>
The script is in the header so it's executed before the other content has been loaded (if jQuery is even active, seeing no reference to it). You should put it in a function and then call it later on (e.g. through onload or a timer). I could as well think of a security feature in the browser, to keep sites from manipulating links right before you click on them.
Here is the code for the correct jQuery way to do this (using the document ready).
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#changeme").attr('href', 'http:\/\/maps.google.com/');
});
</script>
</head>
<body>
<div class="content">
<p>Link to <a id="changeme" href="http://www.google.com/">Google</a>
in the contenttest...</p>
</div>
</body>
</html>