Does document.write remove css styling? - javascript

I'm trying to run the script without removing CSS styling.
For example, here I want the background to be blue still when the random number shows.
function myFunc() {
document.write(Math.floor(Math.random() * 999));
}
body {
background-color: blue;
}
<button onclick="myFunc()">Get random num</button>

Put value inside of another element instead of making new document.
Try:
let s = document.createElement("span");
s.innerHtml = Math.floor(Math.random()*999);
body.appendChild(s);
Edit:
I didn't see that #Chris G answered your question but here is a bit different approach with generating new element for each random instead of replacing it. I guess his answer suits you better.

that is not a good practice
You can try this
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test</title>
<style>
body{
background-color: blue;
}
</style>
</head>
<body>
<p id="text"> </p>
<button onclick="myFunc()">Get random num</button>
<script>
function myFunc(){
document.getElementById("text").innerHTML=( Math.floor(Math.random()*999));
}
</script>
</body>
</html>

Yes, Once you click on the button then your html code changes to:
<html><head></head><body>934</body></html>
It is removing the style as well.
As per Link

Yes, it does. This is because document.write() is overwriting all style and link elements that may be present in the document. document.write() completely overwrites everything in the document.
Example:
function doIt() {
document.write('text')
doSomethingElse() // Will not get executed since the script tags have been removed
}
<button onclick='doIt()'>Use document.write</button>

Related

Is it possible to take a JS var representing an element that has been appended to multiple places, and delete it using the var?

See this fiddle. I have an info var that I can easily append to 2 places. But I'd like to also easily remove it from both places without doing something more complicated like $("p").remove()
I know this seems super not complicated, but in production it's harder. I'm always working with the info var so it'd be great if there was some way to say info.removeInAllInstances() or something
I'm not a master in JQuery, but apparentely remove() removes all instances of something. You could filter by an specific class and remove the paragraphs.
Look this example:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>remove demo</title>
<style>
p {
background: yellow;
margin: 6px 0;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
<p>Hello</p>
how are
<p>you?</p>
<button>Call remove() on paragraphs</button>
<script>
$( "button" ).click(function() {
$( "p" ).remove();
});
</script>
</body>
</html>
I get it on https://api.jquery.com/remove/.

Calling a javascript function in a document created with document.write

I have a web page with a button. The click code is:
var html = ...html string containing visual and script elements...
var view = window.open();
view.document.write(html);
view.init(<parameters>); // see next code block
the html content is:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
html, body {
height: 100%;
margin: 0;
}
</style>
</head>
<body>
<div id="id1"></div>
<script>
function init(<parameters>) {
...work...
}
</script>
</body>
</html>
The problem is with the init function call in chrome: all good if I am in IE, but in chrome I get "init function not defined" exception.
How should I do to get this working in all browsers? Of course I am looking for a solution that doesn't require a server round trip.
IM a noob so idk if this is exaclty true but i have read that ie allows you to do alot more then chrome or firefox. It might be one of those example where ie will let you do something.
using document.write does in fact work when it comes to create the page I want. Problem is when I want to call a function defined in a javascript block inside that page. Different browsers give different results so I guess this is a matter not completely standardized yet. There are posts in the internet about this, but I couldn't find a clear and common answer.
I then solved my impasse with a workaround. The initial markup contains now placeholders for the parameters:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
html, body {
height: 100%;
margin: 0;
}
</style>
</head>
<body>
<div id="id1"></div>
<script>
(init = function () {
var parameter1 = ${{placeholder1}}
var parameter2 = ${{placeholder2}}
...
...work...
})();
</script>
</body>
</html>
The creating code, then, replaces the placeholders with actual values:
var html = ...html string containing placeholders...
html = html.replace("${{placeholder1}}", actual1);
html = html.replace("${{placeholder2}}", actual2);
...
var view = window.open();
view.document.write(html);
Now the init function is called in the same page context, and this works in Chrome as well.
It is not possible to write to a new window if its not on the same domain. What I suggest is that you can open an iframe an work inside that.
How to write to iframe
How to write to page on same domain

document.getElementsByTagName returning undefined on placing the script after body

I know that this is a frequently asked question.
I have tried all the methods like using onload() for body tag,
placing the script after the DOM elements and using self invoking function.
Yet I get that my element is undefined.
P.S: document.getElementsByTagName('') replaced with document.getElementById('') works fine. Why is that? Please explain both of my doubts. Here is my simple code
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body onload="loadHandler()">
<p>Drag me!</p>
<script type="text/javascript">
function loadHandler() {
document.getElementsByTagName('p').setAttribute('draggable', true);
}
</script>
</body>
</html>
getElementsByTagName (as the name suggests) returns an array of elements. If you want the first one, take the first one.
.highlight{ color: red}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body onload="loadHandler()">
<p>Drag me!</p>
<script type="text/javascript">
function loadHandler() {
var elem = document.getElementsByTagName('p')[0];
elem.setAttribute('draggable',true)
elem.classList.add('highlight');
}
</script>
</body>
</html>
As for why dragging is not working, perhaps the documentation might shed some light
By default, only text selections, images, and links can be dragged. For all others elements, the event ondragstart must be set for the drag and drop mechanism to work, as shown in this comprehensive example.
getElementsByTagName returns array of results, not just a single result like getElementById. Try to use getElementsByTagName('p')[0].

Changing JavaScript Font Size in Document Write

I have the following code, and it is doing what I want but I can't get any styling on it, and I was wondering how to do that? I've tried pointing CSS to the body but it still does nothing. My goal is to control the font size, the positioning, and the font colour. Please ignore the CSS call
<!DOCTYPE html>
<html>
<head>
<title> SUCCESS</title>
<link type="text/css" rel="stylesheet" href="SUCCESS.css" media="screen">
</head>
<body>
<script>
document.querySelector("body").addEventListener("keypress", function printer()
{
document.write('SUCCESS');
})
</script>
</body>
</html>
document.write will accept HTML tags. Try something like this
document.write("<p style=''>Success</p>");
But I suggest you the better way is create an HTML element already with styles and change it according using getElementById or something
So easy, use this javascript, look:
function CustomWrite(a,b) {
b = '"'+b+'"';
a = '<span style='+b+'>'+a+'</span>'
return document.write(a);
}
how to use, look:
CustomWrite('SUCESS','you css code here');

$('body').offset().top always returns 8 even with nothing else on the page

I was under the impression that $('body').offset().top should return 0, but apparently it keeps returning 8. I removed all unnecessary code from my webpage and it still returns 8.
Here is what I have:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script>
$(document).ready(function () {
console.log($('body').offset().top);
})
</script>
</body>
</html>
That's literally everything in my code. Here's the JSFiddle: http://jsfiddle.net/Lspkx2su/
Default CSS. Insert this:
<style>
html, body { margin: 0 }
</style>
and try again.
By default the styling for body tag uses up space in the webpage.
Try this code you'll understand -
The HTML
<body>
<div class="wrapper">
Hello World
</div>
</body>
and the following CSS
.wrapper{
border: 1px solid red;
}
When you run the above code, you'll see that your "Hello World" is displayed with a small offset. This is default in HTML/CSS.
However, #amadan is absolutely right. You should always use the following to start your webpage CSS. No offset problem will occur.
body{
margin:0;padding:0;
/* considering your outermost div to be the wrapper of your whole page */
}

Categories

Resources