why does this script only give half the output? [duplicate] - javascript

This question already has answers here:
javascript document.write() removes the html from page and display result in a blank page [duplicate]
(3 answers)
Closed 10 years ago.
Here is the function:
function funct1()
{
document.getElementById("demo").innerHTML="Something";
document.write("Mexico!");
}
The output is only:
Mexico
when I click the button on the page, whereas I wanted the output to be:
Something
Mexico

In this instance document.write() doesn't do what you think. It clears the contents of the document, and writes Mexico! (see Quentin's answer for a more detailed explanation of why that is). If you remove this line, you can see that your first statement is executed correctly.
If you want to update the first paragraph, and also add another, you should use the following code:
function funct1()
{
document.getElementById("demo").innerHTML = "Something";
// Create a new <p> element, set its HTML and then append it:
var newP = document.createElement('p');
newP.innerHTML = 'Mexico!';
document.body.appendChild(newP);
}
You can see a working jsFiddle here.

After setting the innerHTML of demo, you call document.write. Since the document is in a closed state at this time, this makes an implicit call to document.open which erases the entire existing document (including the stuff you just assigned with innerHTML). Then you write Mexico! to the new document.
Never call document.write after the DOM is ready (and avoid doing so at any other time). Use DOM manipulation instead.

Related

Check if a DOM element node actually exists in DOM [duplicate]

This question already has answers here:
HTML element is attached to a document
(5 answers)
Closed 8 months ago.
I'm defining a function that should receive a DOM element node as a parameter.
There is any efficient way to validate if the element node received actually exists in the DOM?
For example if the element node received has been created through Document.createElement() but not appended to the DOM, I want the validation fails.
I already accomplished it with the code below, but I'm afraid that checking for all DOM element nodes is not the best solution for performance.
function checkIfNodeExists(nodeElement) {
return [...document.querySelectorAll("*")].includes(nodeElement);
}
Could someone suggest a better solution or convince me that my solution is already appropriate?
You want to check if an element is in the DOM? You can see if it is in the body.
var div1 = document.createElement("div");
var div2 = document.querySelector("#foo");
console.log(document.body.contains(div1))
console.log(document.body.contains(div2))
<div id="foo"><div>

Javascript code doesn't execute after the page changes [duplicate]

This question already has answers here:
Is there a way to have an onload callback after changing window.location.href?
(3 answers)
Closed 4 years ago.
So, I'm trying to run this code
document.location = "https://stackoverflow.com/questions/ask";
document.onload = function(){document.getElementById("title").value="My question";};
but it turns out that my function doesn't run the function. You can observe this by doing
document.location = "https://stackoverflow.com/questions/ask";
document.onload = function(){document.getElementById("title").value="My question";alert('Hi');};
My question is, what am I doing wrong? Why doesn't the function run?
Something similar was asked here!
Here is a quote of the most important part of the accepted and most upvoted answer:
No, you cannot do it the way you want. Loading a new page closes the current document and starts loading a new document. Any code in your current document will no longer be active when the new page starts to load. - Source: Answer by jfriend00

rules of using javascript GOTO , LABEL etc [duplicate]

This question already has answers here:
How can I use goto in Javascript?
(16 answers)
Closed 9 years ago.
Can anybody help me in understanding the use of goto , label etc in javascript, I have a program where I need to jump directly to a particular block of code...I am trying to use "break labelName" , but its showing an error that "labelName not found". Is there any rule to use label with break or continue
Thanks in advance .
You must be new to javaScript ;)
Anyhow: defining a function is defining your named excess point:
function doSomething(someVariable){
alert(someVariable);
}
So, somewhere else in your code you can now call doSomething('Hello world!');
Calling the function as above is the GOTO part and doSomething correlates to LABEL. As you see you can also pass some parameters (here it's someVariable) to the function (the executing code block) and work with it (like here the alert that causes an alert box showing in your browser showing the assigned value 'Hello world!'.
Maybe this also helps you: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function or http://www.w3schools.com/js/js_functions.asp

What's different between href="javascript:jsfunction();" and onclick="javascript:jsfunction();" [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the difference between the different methods of putting JavaScript code in an <a>?
What's different between
test
and
test
Thank you very much.
The first is only available for the a tag. It's a link, interpreted by your browser as javascript.
The second is a DOM Event and available for all tags.
The first is a link using the javascript protocol to tell the browser to execute everything after that as JavaScript, rather than trying to load the resource that it points to.
On the other hand, the onclick attribute is an actual JavaScript event handler, and shouldn't be used with javascript: at the beginning - it already knows that it's JavaScript so doesn't need to be told to execute it as JavaScript.
However, in the interests of separating out your content (HTML) and functionality (JavaScript), it's better to use neither of the above techniques, and instead add (for example) id attributes to identify your elements and then use JavaScript to bind your event handlers.
HTML:
test
JavaScript:
document.getElementById('test-anchor').onclick = function(event) {
jsFunction();
}
not this #param
test1
success this #param
test2
function jsFunction($this) {
return $this; // not href attribute this #param ; onClick attribute success this #patam
}

Access a DOM element by using its id as var [duplicate]

This question already has answers here:
Do DOM tree elements with IDs become global properties?
(5 answers)
Closed 8 years ago.
I just came across this by accident and I want to check if this is actually supposed to happen.
I have a div in my page with id box. In my Javascript I set a style to a variable named box: box.style.webkitTransform = "yadda yadda".
I thought that box was in scope, declared as var box = document.getElementById('box');, but it is not (the declaration is in another function!). Neither is there a var box defined globally or in any other place.
However the style got assigned just fine. So somehow the elements' id can be used globally in Javascript? Convenient, but I'm afraid to use it. I assume if the name is used for an actual variable it will override this behavior.
Some browsers add 'named elements' as properties of the document or windowobject. See this SO-question, especially the excellent answers from bobince

Categories