How to add css styles to document.write in javascript - javascript

Hello I'm very new to javascript and doing my first steps I was wondering if I could style the content of a variable in the document.write instruction and I came to this.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.style1{
background-color: chartreuse;
}
</style>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
var name1;
name1=prompt("Write your name");
document.write('<p class="style1">'+name1+'</p>');
</script>
</body>
</html>
I got that solved by reviewing some posts here the question is how does this actually work?
document.write('<p class="style1">'+name1+'</p>');
I'm not sure I understand why I need to put ' for this instruction could somebody explain that please thank you btw I'm sorry this is a very basic question but I would like to know also if you guys have some more ways to style a document.write it would be nice to know .

I'd suggest taking a slightly different approach. You can add a div to your HTML with an ID of "test" (or whatever you'd like), then edit the innerHTML of that div like so:
document.getElementById("test").innerHTML = name1;

document.write : Write HTML elements with text directly to the HTML document
var name1;
name1=prompt("Write your name");
document.write('<p class="style1">'+name1+'</p>');
Create a variable named name1
Give a value to name1 variable from user input in prompt alert
Write p element with class style1 and its content is value from name1 to HTML document

document.write(); is writing a text in your HTML File.
so if you write like this:
<script>document.write("<p>blah</p>");</script>
then you are writing html Source like <p>blah</p>.

Related

Wordpress: how to use javascript variables into html body

I'm really new in Wordpress, Javascript and HTML so I know this question is really basic, but I wasn't able to find it solved anywhere.
I want to create some variables in javascript and then display them in my page which is created in Wordpress.
Reading other posts I've found I need to insert a javascript code that at the end stores my variable this way (dummy version):
<script type="javascript">
document.getElementById('test').innerHTML = 'hello';
</script>
And then on the text block I want to display my variable to be displayed I should add this code:
<body>
<p id="test"></p>
</body>
However I've tried adding the javascript in the header (Tatsu header) and also tried adding it in the text block (HTML version) in different combinations and it never worked. Tried adding the script block before and after the body block, and also tried having it inside, before and after the display line.
If I try the following it works:
<body>
<p>hello</p>
</body>
So I guess my problem is that I'm not setting the variable properly.
Can anyone help? Apologies if this is already solved somewhere, spent some hours and wasn't able to find it.
Thank you in advance.
Your problem is the type of which you're using here:
<script type="javascript">
I noticed this whilst constructing an example of this problem.
javascript is not a correct mime type.
It should be text/javascript as per https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
Please note this is not a complete list. Such as application/javascript also being valid. Please also see https://www.iana.org/assignments/media-types/media-types.xhtml
Working example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<p id="test">
This shouldn't show up
</p>
<script type="text/javascript">
console.log("####### JAVASCRIPT IS RUNNING ######")
document.getElementById('test').innerHTML = 'hello';
</script>
</body>
</html>

Can i access html element Id from any from anyfiles?

I am a beginner to Java-script.
i have a concern
on mainPage.html
<div id="showDialog" style="display:none"> </div>
on mainPage.js
$('#ShowDialog').load("../xxxx.html", function (content) {
xxxxxxxxxxx
});
It is easy understand that if you want to use the id element you just call #element
So, my question is here:
if you are in Setup.js (setup.html has no id attribute like #ShowDialog)
can you still call (So, it will do something on mainPage.html ?? )
$('#ShowDialog').load("../xxxx.html", function (content) {
xxxxxxxxxxx
});
If so, is the class also do the same job? i know id is unique and class is common. So, if one file class can be accessed from other file?
like
$('.ShowDialog').load("../xxxx.html", function (content) {
xxxxxxxxxxx
});
By the way, why we call class using $(.'ShowDialog')rather than just call name like $('ShowDialog')
for class="ShowDialog"
If you want to reference an html Element from an external Javascript file it could be as follows:
myHtml.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- First Import Jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Then the module you wish to work with-->
<script src="./ReferencebyId.js"></script>
<title>referencing html Element by Id</title>
</head>
<body>
<!-- the Id you will reference on the module -->
<p id="myId">Change this text</p>
<button onclick="changeInnerHtml()">Change paragraph text</button>
</body>
</html>
ReferencebyId.js
function changeInnerHtml(){
//This is how you would reference the Id, with '#' character
$("#myId").text("changed from external js file referencing Id");
}
Remember that if you wish to use the class to reference the Html Element, you have to make sure only that element has that class, or if you wish to affect more than one element you can put them the same class, and reference them as $(".nameOfClass")
Could you please explain what is it that you are trying to do?
As I understand from your code, you are trying to load content from an external HTML to other HTML with the load function in JQuery and place it inside the div with id="showDialog"
$('#ShowDialog').load("../xxxx.html", function (content) {...}
Is this what you are trying to do? or are you trying to run some JavaScript from other file?
What do you mean by:
setup.html has no id attribute like #ShowDialog
does setup.html does not have any div with that id?
and by:
can you still call (So, it will do something on mainPage.html ?? )
call what? the loader.
about:
By the way, why we call class using $(.'ShowDialog')rather than just call name like $('ShowDialog')
The preceding dot (.) is because classes on jQuery selectors are specified with a preceding dot (.), and id's with a hash sign (#), think of it, like Css selectors, but in jQuery.
Please explain exactly what are you trying to do so we can help you better :)

HTML equivalent of PHP include for JavaScript parts

I'm looking for a Javascript equivalent of a technique I've been using in PHP. That is, to place even the most basic page setup:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
...in a php file like 'doc_start.php' and then start every page in my site with...
<?php require_once('/path/to/doc_start.php); ?>
Now I need to begin a project that's strictly HTML and JS (no PHP) and want a similar way to avoid duplicating basic, common HTML elements. Obviously, I want to do more than this very basic stuff, like import JQuery in every page, link to a common stylesheet, etc. Again, all easy in PHP, but I'm still kind of a newbie in JS.
I've read about HTML5 includes, but can't seem to find anything that addresses what I want to do
In order to import other pages into your current document, you need to use a link tag.
For example....
<head>
<link rel="import" href="/path/to/imports/stuff.html">
</head>
This will allow you to reference other html, css or javascript documents into your page without copying and pasting the same code within each page.
https://www.w3schools.com/html/html_links.asp
Javascript and PHP are different languages for very different purposes. But assuming you have some element you don't want to repeat some elements one solution is the following:
Save the HTML elements that you don't want to keep repeating as a string. Then use the .innerHTML property to add elements.
The .innerHTML property stores the mark up of an element as a string.
For example, if we have the following <div>:
<div class="example"> <br> Hello there this is a test! </div>
...and we use .innerHTML:
console.log(document.querySelector(".example").innerHTML);
It will output "<br> Hello there this is a test!".
We can add to the .innerHTML using the += operator. So if you want to add something inside the body it's as simple as:
var something = "some HTML";
document.body.innerHTML += something;
Hope this was what you were looking for!

Js, document.getElementById("ID").innerHTML, error

Hello I'm new to javascript, and I'm try to write out some code for a test site and I'm having some problems, dow below is my code and I keep getting this error and i can't figure out why.
TypeError: null is not an object (evaluating 'document.getElementById("h3").innerHTML = "<h3>You Are up to date!</h3>"')
This is my second method i tried using. what I'm trying to do it have a have a version list this first one i had was that it would pull a .js file and build a table, but that didn't work so i thought i would try this, but guess what happened? not working
my code that I'm using now is below. if you can help that would be amazing.
thanks, Dakmessier
var current = "1.0";
function get_latest(){
document.getElementById("bob").innerHTML = current;
}
if (local != current){
document.getElementById("Get").innerHTML = "<button>Get the Latest Update!</button>";
} else if (local == current){
document.getElementById("h3").innerHTML = "<h3>You Are up to date!</h3>";
} else {
document.getElementById("h3").innerHTML = "<h3>Sorry, unable to check for update.</h3>";
}
document.getElementById(id) finds an element with a given id value in your HTML. An id value looks like this:
<div id="myHeader">Some Content</div>
And, then you can find that element with:
document.getElementById("myHeader");
ID values must be unique in each document so there should only ever be one element with a given ID.
If an id isn't what you really want, you can find elements other ways, by tag type, by class name, by attribute, etc... using CSS selectors with document.querySelectorAll().
For example, if you wanted to find all <h3> tags, you could do this:
var items = document.querySelectorAll("h3");
Here are some other reasons that document.getElementById(...) might fail to find what you want it to find:
The Javascript code is running before the DOM elements have been parsed and loaded so thus the element is actually not there yet when you're running the code. This is common with code run from the <head> section of the document.
You have an HTML error in how you are specifying the id value in the HTML.
You have an HTML error that causes the browser not to parse your HTML properly.
You have a script error that cause your script to abort before it gets to the part you want to run.
Indeed document.getElementById returns null if it can't find an element with the Id specified.
Also the statement:
if (local != current){
// ..
} else if (local == current){
// ..
} else {
// ..
}
is a bit odd. If local != current is false then local == current must be true. The else if (...) is redundant and the else part will never be run.
hey man the bast thing you should do is the following example, feel free to copy it on your snippet of code:
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed!";
}
<!DOCTYPE html>
<html>
<body>
<p id="demo" onclick="myFunction()">Click me to change my HTML content (innerHTML).</p>
</body>
</html>
I WILL EXPLAIN YOU THIS ANSWER: this is an html + an inline script that makes the inner html work. As far as concerned with your answer it was unclear where your code stopped, anyway test my snippet of code and let me know
I know it's an old question, but I was having the same issue and was trying hard to find the solution for some time.
The problem was that I was executing the script before the page loaded. Thus it wasn't able to find the object that we're trying to catch.
So either use jquery document.ready function or else move your script to the end of the html.
I hope this helps
fix an error of getting the value of a as null
Uncaught TypeError: a is null
code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script>
let a = document.getElementById('i');
document.addEventListener('mouseup',function(){
a.innerHTML='clean';
})
</script>
<body>
<h3 id="i">not clean</h3>
</body>
</html>
this shows as error in console as
Uncaught TypeError: a is null
you can fix it by making your script tag before
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h3 id="i">not clean</h3>
<script>
let a = document.getElementById('i');
document.addEventListener('mouseup',function(){
a.innerHTML='clean';
})
</script>
</body>
</html>
this might fix!!

embed HTML tag in JavaScript

I'd like to embed an html tag in Javascript, between the script> tag
Thanks
Hey maybe you're looking for jQuery.
$("p").text("<b>Some</b> new text.");
See embedded HTML tag.
Write Less, Do More
jQuery
Is E4X what you're looking for? It allows you to embed XML/XHTML within your JavaScript, like this:
var someXml = <div><b>Some Text</b></div>;
I doubt that's what you need, but that's the only way you can do what you're asking. Also, I don't think it works in Internet Explorer. Scratch that, it only works in Firefox.
If that's not what you want, use document.write(), as suggested by others.
Edit: E4X is now deprecated and has been removed from newer versions of Firefox. Don't use it. You should use jQuery, as the answer below me suggests, or simply create the elements via document.createElement and friends and inject them into the document.
You can't. If you want the Javascript to write HTML, you'll have to use document.write().
If you write this inside your body tag then also you can access this using your javascript.
If yo want to check whether the document is ready or not then you can use JQuery
You can't do that. tags can contain just text (usually javascript).
document.write('colour1: ' + colour1 + 'colour2: ' + colour2 + '');
Using document.write(), though it is generally advised against the use of this method.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
document.write(`
<html>
<body>
<p>html in script tag</p>
<\/body>
<\/html>
`)
</script>
</body>
</html>

Categories