This question already has answers here:
Javascript can't find element by id? [duplicate]
(5 answers)
Closed 4 years ago.
The following line of code (in my Javascript file) :-
var header = document.getElementById("theheader");
is resulting in header having a "null" value. Here, "theheader" is the ID of a "h2" type header in my HTML file.
The desired output is:-
<h2 id="theheader" style="color: rgb(114, 58, 76);">
The script tag of the JS file is defined within the head element of the HTML file.
The same line of code would work perfectly in any browser console by giving the desired output i.e.
Even though this issue has been handled before, I could not find the answer as to why the same code above is working in the browser console and not working in IDE's like VSCode, Atom and others?
I would be thankful if anyone could provide me the answer for the above query, specially the one in bold font.
One possible reason could be that your code is running before the DOM is fully loaded. Wrap your code with DOMContentLoaded:
The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
<script>
document.addEventListener("DOMContentLoaded", function(event) {
//Intro
alert("Hey! Welcome to my page!!");
var a = prompt("How are you today?");
alert("Happy to know that you are " + a);
var header = document.getElementById("theheader");
console.log("h2 is " + header);
header.style.color = "red";
function getRandomColor() {
var letters = "0123456789ABCDEF";
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function changeHeaderColor(){
colorInput = getRandomColor()
header.style.color = colorInput;
}
setInterval(changeHeaderColor,500);
});
</script>
<h2 id = "theheader"> Arnab Sinha </h2>
Related
I'm using javascript for the first time and am having difficulty getting certain features to work. Crucially I can't seem to get the following line of code to execute.
document.getElementByID("reportImage").src=filepath;
The full code is given below.
Notice that I've created a test function to try and narrow down the cause of the malfunction. The first two functions are there to demonstrate intent but are not currently being called by the .
The behavior of the test function suggests that the error is within this specific line. Notably the alert will fire if it is placed first in the function but will not trigger if placed second (suggesting that this specific line is problematic in some way).
It may be a simple syntax error but I've checked many times and can't see what it might be. Please help!
<!DOCTYPE html>
<html>
<script>
/* declare and set script variables */
var numberOfImages, imageArray, timing, containingFolder, i;
i = -1;
timing = 3;
containingFolder = "H:\\Images";
imageArray = [
"FoxKey.jpg",
"TeamKPI2.tif"
]; //imageArray should contain names of image files that sit within the specified folder
numberOfImages = imageArray.length;
function activateImageTimer() {
/* function iterates through selected images */
if (numberOfImages === timingArray.length) {
setInterval(nextImage(), timing*10);
}
else { alert("Please check contents of imageArray and timingArray. The
number of images should correspond to the number of timings."); }
}
function nextImage() {
i = (i+1) % numberOfImages; //use modulus function to loop through array
var filepath = containingFolder + "\\" + imageArray[i]; //build filepath
document.getElementByID("reportImage").src=filepath;
}
function testFunction() {
document.getElementByID("reportImage").src="H:\\Images\\FoxKey.jpg";
alert("Function is functioning");
}
</script>
<body onload="testFunction()">
<img id="reportImage" src="H:\Images\TeamKPI2.tif">
</body>
</html>
JavaScript is Case Sensitive.
Try with this:
Change: document.getElementByID to document.getElementById
And, <script></script> it has to be put inside the body or head, not of html.
My function is as follows:
function mySound() {
var eventTable = document.querySelector("#eventContent");
var eventCella=eventTable.getElementsByClassName("ago_eventlist_activity");
var eventCellb = eventTable.getElementsByClassName("missionFleet");
for (var i = 0; i < eventTable.rows.length-1; i++) {
var cella = eventCella[i];
var cellb = eventCellb[i];
if (cella.src == "Activity15.gif" && cellb.src == "60a018ae3104b4c7e5af8b2bde5aee.gif")
{theSound = probeSound; oaPlaySound();}
if (cella.img == "Activity15.gif" && cellb.img == "cd360bccfc35b10966323c56ca8aac.gif")
{theSound = attackSound; oaPlaySound();}
if (cella.img == "Activity15.gif" && cellb.img == "575dfbbe877f58d6c09120ffbcaabe.gif") {theSound = attackSoundRIP; oaPlaySound();}
} /* for i */
}
*I can't use ...byid cause it doesn't seem to have one?
I am including a link to the FireFox inspect element so you can see what I can see to try to make this work.
Image of InspectElement:
Any help would be helpful I am just trying to code this for a friend and I really don't know java at all.
Thanks
There is a difference between Java and javascript. I'm guessing you mean javascript since that is what the code appears to be.
There are a few issues with the code
cella.img does not target the image inside of the cell, you'll need to target the image first, or use find the image inside the cell.
var eventCella = eventTable.querySelector(".missionFleet img");
or
var imgb = eventCellb[i].querySelector("img");
Does the ago_eventlist_activity cell even contain an image? There doesn't seem to be one in the screenshot.
Checking the image src needs to include the complete url, unless you use an indexOf...
if (imgb.src.indexOf('60a018ae3104b4c7e5af8b2bde5aee.gif') > -1) {
// do something
}
I hope that helps. Please, the next time you ask a question, include the HTML instead of a screenshot. Or better yet, include a demo (jsFiddle) that shows the problem because it makes it easier for others to help. Not everyone will take the time or make an effort.
I am new to web developing, and I have met this problem. I write the following script:
<script>
function updateProductQuantity(num,index)
{
var inp = document.getElementById("input-"+index);
var tot = document.getElementById("total-"+index);
var n_quantity = inp.value;
if (!isNaN(n_quantity))
{
addArticle(num, null, {"quantity":"set_"+n_quantity});
inp.value = parseInt(inp.value);
}
else window.alert("Not a number: " + n_quantity);
}
</script>
In chorme, (also firefox) this appears like this:
<p> <script>
function updateProductQuantity(num,index)
{
var inp=document.getElementById("input-"+index);
var tot=document.getElementById("total-"+index);
var n_quantity=inp.value;</p>
<p> if (!isNaN(n_quantity))
{
addArticle(num,null, {"quantity":"set_"+n_quantity});
inp.value = parseInt(inp.value);
}
else window.alert("Not a number:" + n_quantity);
}
</script></p>
(both firefox and chrome insert these p tags)
In the browzer, the whole script appears to be inside a "p" element, which I do not write in the code.
Also, the empty lines of my code are converted into p tags.
Of course, the script is broken and I get this error:
Uncaught SyntaxError: Unexpected token <
A workaround is to remove all empty lines from the come. But I dont think this is a solution. Right?
Thanks in advance!
Without seeing all of your code my best guess would be that you've got something else going on like an unclosed tag that is confusing matters.
Try putting the contents of your file through W3C's validator https://validator.w3.org/#validate_by_input and fix any errors that it is showing you
I have a hotfix app which generates HTML slides. The modules are built in Jquery with the background as inline CSS (the best solution i could come up with since they are unique per instance).
The problem is that firefox converts the quotes in the style attribute into:
<div style="background-image: url("bigspace-template.jpg");"
class="nuiOpenspace t1 skin1">
The webkit browsers have no issues with this.
They only way i have been able to get the background attribute is by:
// Build function, shortened
openspace.build = function(){
// ...
var bgstr = 'background-image: url('+ this.val_image + ')';
$o = $('<div class="nuiOpenspace"></div>').attr('style', bgstr);
// ...
}
This is then output appended to the document:
function Sandbox(){
var $sandbox = $("#sandbox");
this.fill = function(o) {
$sandbox.empty();
$sandbox.append(o);
};
// ...
}
I then get the HTML from the dom, convert to string and then output it in a textarea:
function Source(){
this.print = function(o, c_val){
//var parsed_html = this.parse(o, c_val);
//var pretty_html = "";
//pretty_html = style_html( parsed_html );
//console.info(x.replaceAll('&qout;', 'x'));
$code.text( style_html($("#sandbox").html()) );
};
}
var source = new Source();
I´ve tried search and replace but firefox keeps changing to / adding ". Any ideas?
As far as I know, the " is a ", so you have " inside something that is in between its own ". That can never work like this I think.
If you would've changed the origional code (the one that didn't work in firefox) to valid code (using either escapes or a combination of ' and " instead of "nested" "), wouldn't you be closer to a solution?
I'm working on a web page where I'm making an AJAX call that returns a chunk of HTML like:
<div>
<!-- some html -->
<script type="text/javascript">
/** some javascript */
</script>
</div>
I'm inserting the whole thing into the DOM, but the JavaScript isn't being run. Is there a way to run it?
Some details: I can't control what's in the script block (so I can't change it to a function that could be called), I just need the whole block to be executed. I can't call eval on the response because the JavaScript is within a larger block of HTML. I could do some kind of regex to separate out the JavaScript and then call eval on it, but that's pretty yucky. Anyone know a better way?
Script added by setting the innerHTML property of an element doesn't get executed. Try creating a new div, setting its innerHTML, then adding this new div to the DOM. For example:
<html>
<head>
<script type='text/javascript'>
function addScript()
{
var str = "<script>alert('i am here');<\/script>";
var newdiv = document.createElement('div');
newdiv.innerHTML = str;
document.getElementById('target').appendChild(newdiv);
}
</script>
</head>
<body>
<input type="button" value="add script" onclick="addScript()"/>
<div>hello world</div>
<div id="target"></div>
</body>
</html>
You don't have to use regex if you are using the response to fill a div or something. You can use getElementsByTagName.
div.innerHTML = response;
var scripts = div.getElementsByTagName('script');
for (var ix = 0; ix < scripts.length; ix++) {
eval(scripts[ix].text);
}
While the accepted answer from #Ed. does not work on current versions of Firefox, Google Chrome or Safari browsers I managed to adept his example in order to invoke dynamically added scripts.
The necessary changes are only in the way scripts are added to DOM. Instead of adding it as innerHTML the trick was to create a new script element and add the actual script content as innerHTML to the created element and then append the script element to the actual target.
<html>
<head>
<script type='text/javascript'>
function addScript()
{
var newdiv = document.createElement('div');
var p = document.createElement('p');
p.innerHTML = "Dynamically added text";
newdiv.appendChild(p);
var script = document.createElement('script');
script.innerHTML = "alert('i am here');";
newdiv.appendChild(script);
document.getElementById('target').appendChild(newdiv);
}
</script>
</head>
<body>
<input type="button" value="add script" onclick="addScript()"/>
<div>hello world</div>
<div id="target"></div>
</body>
</html>
This works for me on Firefox 42, Google Chrome 48 and Safari 9.0.3
An alternative is to not just dump the return from the Ajax call into the DOM using InnerHTML.
You can insert each node dynamically, and then the script will run.
Otherwise, the browser just assumes you are inserting a text node, and ignores the scripts.
Using Eval is rather evil, because it requires another instance of the Javascript VM to be fired up and JIT the passed string.
The best method would probably be to identify and eval the contents of the script block directly via the DOM.
I would be careful though.. if you are implementing this to overcome a limitation of some off site call you are opening up a security hole.
Whatever you implement could be exploited for XSS.
You can use one of the popular Ajax libraries that do this for you natively. I like Prototype. You can just add evalScripts:true as part of your Ajax call and it happens automagically.
For those who like to live dangerously:
// This is the HTML with script element(s) we want to inject
var newHtml = '<b>After!</b>\r\n<' +
'script>\r\nchangeColorEverySecond();\r\n</' +
'script>';
// Here, we separate the script tags from the non-script HTML
var parts = separateScriptElementsFromHtml(newHtml);
function separateScriptElementsFromHtml(fullHtmlString) {
var inner = [], outer = [], m;
while (m = /<script>([^<]*)<\/script>/gi.exec(fullHtmlString)) {
outer.push(fullHtmlString.substr(0, m.index));
inner.push(m[1]);
fullHtmlString = fullHtmlString.substr(m.index + m[0].length);
}
outer.push(fullHtmlString);
return {
html: outer.join('\r\n'),
js: inner.join('\r\n')
};
}
// In 2 seconds, inject the new HTML, and run the JS
setTimeout(function(){
document.getElementsByTagName('P')[0].innerHTML = parts.html;
eval(parts.js);
}, 2000);
// This is the function inside the script tag
function changeColorEverySecond() {
document.getElementsByTagName('p')[0].style.color = getRandomColor();
setTimeout(changeColorEverySecond, 1000);
}
// Here is a fun fun function copied from:
// https://stackoverflow.com/a/1484514/2413712
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
<p>Before</p>