Changing innerHTML of div clears the whole content - javascript

Aka: why are <div></div> and <div /> not equivalent to each other?
Consider the following HTML + js:
setTimeout(function() {
document.getElementById("message2").innerHTML = "blah";
}, 1000);
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="message2" />
<div id="message1" >Hello</div>
</body>
</html>
As you can see, when executing the snippet, first "Hello" is shown, and briefly afterwards, "Hello" disappears (*) and "blah" is shown. (I.e. the innerHTML of message2 was changed, and, as a side-effect, message1 disappeared.)
(*) I checked this on two different browsers (Linux/FF and Mac/Safari), so I'm quite confident this is not a browser-specific issue.
If, on the other hand, message2 is expanded to opening/closing tags, then changing its innerHTML won't affect message1:
setTimeout(function() {
document.getElementById("message2").innerHTML = "blah";
}, 1000);
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="message2" ></div> <!-- notice that it was expanded -->
<div id="message1" >Hello</div>
</body>
</html>
Questions:
Why does the other div disappear in the first case?
Why do the "compact" and the "expanded" form have different effects? (I thought they were fully equivalent.)

This div <div id="message2" /> is not closed as you think it is. Here is a list of HTML's self closing tags. Note that div is not one of them.
See this:
setTimeout(function() {
document.getElementById("message2").innerHTML = "blah";
}, 1000);
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="message2" >
<div id="message1" >Hello</div>
</div>
</body>
</html>
So in your second snippet you just change innerHTML of the first div, while second just sits there.

Related

JavaScript (Alert Message)

I have written a JavaScript alert message code it displays the alert message first in both codes 1 and 2 before Html content. What should I do to run the HTML content first and then a javascript code?
Code 1
<!DOCTYPE html>
<html>
<head>
<title>Hello, World !</title>
</head>
<body>
<h1>I am learning JavaScript.</h1>
<div id="Content">
<p>This is a paragraph tag. Here the content of html.</p>
</div>
<script src="text.js"></script>
</body>
</html>
Code 2
<!DOCTYPE html>
<html>
<head>
<title>Hello, World !</title>
</head>
<body>
<h1>I am learning JavaScript.</h1>
<div id="Content">
<p>This is a paragraph tag. Here the content of html.</p>
</div>
<script>
alert(" This is alert message.");
</script>
</body>
</html>
There is a load event, which will fire AFTER the page is loaded. You can listen to the event:
window.addEventListener('load', function() {
console.log('All assets are loaded');
alert ("This is an alert MSG");
})
You can use setTimeout() for this
<html>
<head>
<title>Hello, World !</title>
</head>
<body>
<h1>I am learning JavaScript.</h1>
<div id="Content">
<p>This is a paragraph tag. Here the content of html.</p>
</div>
<script>
setTimeout(()=>{
alert(" This is alert message.")
},2000)
</script>
</body>
</html>
You can use window.onload function. This function called after body load.
<!DOCTYPE html>
<html>
<head>
<title>Hello, World !</title>
</head>
<body>
<h1>I am learning JavaScript.</h1>
<div id="Content">
<p>This is a paragraph tag. Here the content of html.</p>
</div>
<script>
window.onload = function () {
alert(" This is alert message.");
}
</script>
</body>
</html>
In your first code just put defer attribute as below
<script defer src="text.js"></script>
A script that will be downloaded in parallel to parsing the page, and executed after the page has finished parsing
for more detail refer to the URL
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script
create your Script like below
<script type = "text/javascript">
function displayalert() {
alert ("This is an alert MSG");
}
</script>
add this code in your body(this is a button)
<input type = "button" value = "Click me" onclick = "displayalert();" />
when you click on this button you will see the alert
We are using the onclick attribute and call the displayalert() function where the alert() is defined.

Can't change text in button

Here is the code from the book "HTML 5 + JS for Dummies", looking at it for more than 2 hours and can't find a reason why it doesn't want to work. I'm in very early stage and sorry for my newb question.
<!DOCTYPE html>
<html>
<head>
<title> Outputting data to HTML </title>
<script language ="JavaScript">
{
document.getElementById("myText").
innerHTML ="Clicked!";
}
</script>
</head>
<body>
<h1> Creating HTML Element Output </h1>
<div> <p id="myText">Change Me </p> </div>
<div>
<input id="btnClickMe"
type="button"
value = "Click me"
onlick="WriteText()"/>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title> Outputting data to HTML </title>
<script>
function WriteText()
{
document.getElementById("myText").
innerHTML ="Clicked!";
}
</script>
</head>
<body>
<h1> Creating HTML Element Output </h1>
<div> <p id="myText">Change Me </p> </div>
<div>
<input id="btnClickMe"
type="button"
value = "Click me"
onclick="WriteText()"/>
</div>
</body>
</html>
Here's what i did/what was wrong:
You have used wrong syntax for functions or you forgot to use the function keyword
You misspelled onclick (onlick)
I moved the script part out of the head
Use setAttribute method because input filed have not innerHTML property.
`<script language ="JavaScript">
function WriteText()
{
document.getElementById("myText").setAttribute("value", "Clicked!");
}
</script>
</head>
`

Changing element text isn't working

It always seems to be a problem and I fail to see why, I'm trying to change element p text by using his ID, element p id="para1" is inside PostEditor.html:
The elementID I want to change is para1 in the following html:
<!DOCTYPE html>
<html>
<head>
<title>Editor</title>
<link href="styles/editor.css" rel="stylesheet" type="text/css" media="screen" />
<script src="scripts/mainScript.js"> </script>
</head>
<body>
<!-- Input fields -->
<div class="center">
<form id=caller method="post">
<p id="para1" class="text"><Strong>Post your message</Strong></p>
<textarea id="textEditor" rows="16" cols="34" name="content"></textarea>
<input type="submit" onclick="urlLoader('caller','posthandler.php')" value="Post">
</form>
</div>
<!-- end Input fields -->
</body>
</html>
The following function is issued by a click on a link inside index.html and displaying the page you are seeing above and is then supposed to change its content:
From index.html I issue the function from link:
<a onclick="postEditing()"> Edit</a>
This line issue the following function:
function postEditing()
{
var result = window.open('PostEditor.html', 'newwindow', 'width=350,' + 'height=350');
result.document.getElementById("para1").innerHTML = "11111111111";
result.document.getElementById("para1").innerText = "11111111111";
result.document.getElementById("para1").value = "11111111111";
}
As you can see I tried three methods. I'd never understand what is the difference between them, but I tried all three and none worked!
It's because you're searching the document of the window which shows the index.html, not the document of the newly opened window. try following:
...
var editorWindow = window.open('PostEditor.html', 'newwindow', 'width=350,' + 'height=350');
editorWindow.document.getElementById("para1").innerHTML = "11111111111";
...
EDIT:
NOW i see the problem: in the function you're trying to access a property of the parameter element, but you don't pass a value for it. So this will end in an error because the accessed object is undefinded!
So you have three options to get it working:
test the parameter (always a good idea): var ID = null; if(element) ID = element.id;
pass a value: <a onclick="postEditing(this)"> Edit</a>
remove the line var ID = element.id;
SOLUTION: (TESTED)
I could not really say why, but the index.html found the para1 and can successfully set the new text. But somehow the new window will reinitialize the old value again.
So you have to do the changing in an handler you run at onLoad:
index.html:
<html>
<head>
<script>
function postEditing() {
var result = window.open('PostEditor.html', 'newwindow', 'width=350,' + 'height=350');
result.onload = function() {
result.document.getElementById("para1").innerHTML = "11111111111";
}
}
</script>
</head>
<body>
<a onclick="postEditing()"> Edit</a>
</body>
</html>
PostEditor.html:
<!DOCTYPE html>
<html>
<head>
<title>Editor</title>
<link href="styles/editor.css" rel="stylesheet" type="text/css" media="screen" />
<script src="scripts/mainScript.js"> </script>
</head>
<body>
<!-- Input fields -->
<div class="center">
<form id=caller method="post">
<p id="para1" class="text"><Strong>Post your message</Strong></p>
<textarea id="textEditor" rows="16" cols="34" name="content"></textarea>
<input type="submit" onclick="urlLoader('caller','posthandler.php')" value="Post">
</form>
</div>
<!-- end Input fields -->
</body>
</html>
I'm fairly sure you will need to query the return result of calling window.open like this:
function postEditing(element)
{
var ID = element.id;
var result = window.open('PostEditor.html', 'newwindow', 'width=350,' + 'height=350');
result.getElementById("para1").innerHTML = "11111111111";
result.getElementById("para1").innerText = "11111111111";
result.getElementById("para1").value = "11111111111";
}
[Untested though]
Your button type is submit, which is posting the form. The object is changing in the DOM, only after the script runs, the DOM is reloaded back to it's original state. Try changing your button type to "button", and you should see the P element change appropriately.
Edit: Here's the HTML I used to determine the above. Keeping the button as "submit" caused me to see the text change and then swap back. The HTML below should keep the text in place. HTH!
<!DOCTYPE html>
<html>
<head>
<title>Editor</title>
<script>
function postEditing(element)
{
document.getElementById('para1').innerHTML = "asdafs";
}
</script>
</head>
<body>
<!-- Input fields -->
<div class="center">
<form id=caller method="post">
<p id="para1" class="text"><Strong>Post your message</Strong></p>
<textarea id="textEditor" rows="16" cols="34" name="content"></textarea>
<input type="button" onclick="postEditing('caller')" value="Post">
</form>
</div>
<!-- end Input fields -->
</body>
</html>

Move Div when above Div Filled

i have 2 div with relative position
user with a button fill first Div(innerHTML)
i want second Div move down when first Div Filled
show below link
Demo
Like this? jsFiddle
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type='button' value='Add' onclick='AddEl()' />
<div style='position:relative;background-color:Red'>
01
<div id='Content' style='position:relative;background-color:Green'>
</div>
</div>
<div style='position:relative;background-color:Blue'>
Hagh
<div>
<script>
function AddEl()
{
document.getElementById('Content').innerHTML='Ya';
}
</script>
</body>
</html>
​
You had the nesting wrong in the <div>s.
It was really hard to understand your question, next time please write full sentences.
But I think I understood what you want to achieve.You can't just keep open divs, you have to close them. after the div just write </div>.If you open a div inside a div at least have some styling or other content, beside the inner-div, inside the parent-div.Fix those and it will work for you.
Here is the fixed code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type='button' value='Add' onclick='AddEl()' />
<div style='position:relative;background-color:Red'>
01
</div>
<div id='Content' style='position:relative;background-color:Green'>
</div>
<div style='position:relative;background-color:Blue'>
Hagh
</div>
</body>
<script>
function AddEl()
{
document.getElementById('Content').innerHTML='Ya';
}
</script>
</html>

How do I print part of a rendered HTML page in JavaScript?

The JavaScript code window.print() can print the current HTML page.
If I have a div in an HTML page (for example, a page rendered from an ASP.NET MVC view), then I want to print the div only.
Is there any jQuery unobtrusive JavaScript or normal JavaScript code to implement this request?
Making it more clear, suppose the rendered HTML page is like:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head" runat="server">
<title>
<asp:ContentPlaceHolder runat="server" ID="TitleContent" />
</title>
</head>
<body>
<div id="div1" class="div1">....</div>
<div id="div2" class="div2">....</div>
<div id="div3" class="div3">....</div>
<div id="div4" class="div4">....</div>
<div id="div4" class="div4">....</div>
<p>
<input id="btnSubmit" type="submit" value="Print" onclick="divPrint();" />
</p>
</body>
</html>
Then I want to click on the Print button, only printing div3.
I would go about it somewhat like this:
<html>
<head>
<title>Print Test Page</title>
<script>
printDivCSS = new String ('<link href="myprintstyle.css" rel="stylesheet" type="text/css">')
function printDiv(divId) {
window.frames["print_frame"].document.body.innerHTML=printDivCSS + document.getElementById(divId).innerHTML;
window.frames["print_frame"].window.focus();
window.frames["print_frame"].window.print();
}
</script>
</head>
<body>
<h1><b><center>This is a test page for printing</center></b><hr color=#00cc00 width=95%></h1>
<b>Div 1:</b> Print<br>
<div id="div1">This is the div1's print output</div>
<br><br>
<b>Div 2:</b> Print<br>
<div id="div2">This is the div2's print output</div>
<br><br>
<b>Div 3:</b> Print<br>
<div id="div3">This is the div3's print output</div>
<iframe name="print_frame" width="0" height="0" frameborder="0" src="about:blank"></iframe>
</body>
</html>
Along the same lines as some of the suggestions you would need to do at least the following:
Load some CSS dynamically through JavaScript
Craft some print-specific CSS rules
Apply your fancy CSS rules through JavaScript
An example CSS could be as simple as this:
#media print {
body * {
display:none;
}
body .printable {
display:block;
}
}
Your JavaScript would then only need to apply the "printable" class to your target div and it will be the only thing visible (as long as there are no other conflicting CSS rules -- a separate exercise) when printing happens.
<script type="text/javascript">
function divPrint() {
// Some logic determines which div should be printed...
// This example uses div3.
$("#div3").addClass("printable");
window.print();
}
</script>
You may want to optionally remove the class from the target after printing has occurred, and / or remove the dynamically-added CSS after printing has occurred.
Below is a full working example, the only difference is that the print CSS is not loaded dynamically. If you want it to really be unobtrusive then you will need to load the CSS dynamically like in this answer.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Print Portion Example</title>
<style type="text/css">
#media print {
body * {
display:none;
}
body .printable {
display:block;
}
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<h1>Print Section Example</h1>
<div id="div1">Div 1</div>
<div id="div2">Div 2</div>
<div id="div3">Div 3</div>
<div id="div4">Div 4</div>
<div id="div5">Div 5</div>
<div id="div6">Div 6</div>
<p><input id="btnSubmit" type="submit" value="Print" onclick="divPrint();" /></p>
<script type="text/javascript">
function divPrint() {
// Some logic determines which div should be printed...
// This example uses div3.
$("#div3").addClass("printable");
window.print();
}
</script>
</body>
</html>
Try this JavaScript code:
function printout() {
var newWindow = window.open();
newWindow.document.write(document.getElementById("output").innerHTML);
newWindow.print();
}
<div id="invocieContainer">
<div class="row">
...Your html Page content here....
</div>
</div>
<script src="/Scripts/printThis.js"></script>
<script>
$(document).on("click", "#btnPrint", function(e) {
e.preventDefault();
e.stopPropagation();
$("#invocieContainer").printThis({
debug: false, // show the iframe for debugging
importCSS: true, // import page CSS
importStyle: true, // import style tags
printContainer: true, // grab outer container as well as the contents of the selector
loadCSS: "/Content/bootstrap.min.css", // path to additional css file - us an array [] for multiple
pageTitle: "", // add title to print page
removeInline: false, // remove all inline styles from print elements
printDelay: 333, // variable print delay; depending on complexity a higher value may be necessary
header: null, // prefix to html
formValues: true // preserve input/form values
});
});
</script>
For printThis.js souce code, copy and pase below URL in new tab
https://raw.githubusercontent.com/jasonday/printThis/master/printThis.js
You could use a print stylesheet, but this will affect all print functions.
You could try having a print stylesheet externalally, and it is included via JavaScript when a button is pressed, and then call window.print(), then after that remove it.

Categories