Javascript variable access in HTML - javascript

Say I have the following JavaScript in a HTML page
<html>
<script>
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
</script>
<body>
<a href = test.html>I need the value of "splitText" variable here</a>
</body>
</html>
How do I get the value of the variable "splitText" outside the script tags.
Thanks!

<html>
<script>
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
window.onload = function() {
//when the document is finished loading, replace everything
//between the <a ...> </a> tags with the value of splitText
document.getElementById("myLink").innerHTML=splitText;
}
</script>
<body>
<a id="myLink" href = test.html></a>
</body>
</html>

Try this :
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
$("#target").text(splitText);
});
</script>
<body>
<a id="target" href = test.html></a>
</body>
</html>

<html>
<head>
<script>
function putText() {
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
document.getElementById("destination").innerHTML = "I need the value of " + splitText + " variable here";
}
</script>
</head>
<body onLoad = putText()>
<a id="destination" href = test.html>I need the value of "splitText" variable here</a>
</body>
</html>

In raw javascript, you'll want to put an id on your anchor tag and do this:
<html>
<script>
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
function insertText(){
document.getElementById('someId').InnerHTML = splitText;}
</script>
<body onload="insertText()">
I need the value of "splitText" variable here
</body>
</html>

Here you go: http://codepen.io/anon/pen/cKflA
Although, I must say that what you are asking to do is not a good way to do it. A good way is this: http://codepen.io/anon/pen/jlkvJ

The info inside the <script> tag is then processed inside it to access other parts. If you want to change the text inside another paragraph, then first give the paragraph an id, then set a variable to it using getElementById([id]) to access it ([id] means the id you gave the paragraph).
Next, use the innerHTML built-in variable with whatever your variable was called and a '.' (dot) to show that it is based on the paragraph. You can set it to whatever you want, but be aware that to set a paragraph to a tag (<...>), then you have to still put it in speech marks.
Example:
<!DOCTYPE html>
<html>
<body>
<!--\|/id here-->
<p id="myText"></p>
<p id="myTextTag"></p>
<script>
<!--Here we retrieve the text and show what we want to write...
var text = document.getElementById("myText");
var tag = document.getElementById("myTextTag");
var toWrite = "Hello"
var toWriteTag = "<a href='https://stackoverflow.com'>Stack Overflow</a>"
<!--...and here we are actually affecting the text.-->
text.innerHTML = toWrite
tag.innerHTML = toWriteTag
</script>
<body>
<html>

Related

adding a p tag to the footer using JavaScript

The code should enter "new text" after the Footer text but I'm having issues loading the function.
function insertParagraph(){
var newElement = document.createElement("p");
var node = document.createTextNode("new text");
newElement.appendChild(node);
var element = document.getElementsByTagName("footer");
element.appendChild(newElement);
}
<!DOCTYPE html>
<html>
<body>
<footer>
<P>Footer</P>
</footer>
<script src="main.js"></script>
</body>
</html>
The problem is that getElementsByTagName() returns a collection of elements and collections don't have an .appendChild method. You have to append on to a single element.
Also, you need to call your function so it can run.
function insertParagraph(){
var newElement = document.createElement("p");
newElement.textContent = "new text"; // No need for an explicit text node, just set the text directly
// querySelector() finds the first element that matches the selector argument
document.querySelector("footer").appendChild(newElement);
}
insertParagraph(); // You must call a function so it can run.
<!DOCTYPE html>
<html>
<body>
<footer>
<P>Footer</P>
</footer>
<script src="main.js"></script>
</body>
</html>
function insertParagraph(){
var newElement = document.createElement("p");
var node = document.createTextNode("new text");
newElement.appendChild(node);
var element = document.getElementByTagName("footer");
element.appendChild(newElement);
}
insertParagraph();

script with the phone number to be replaced for that page

So I tried this. I put the required code in the head:
<script type="text/javascript">
var callback = function(formatted_number, mobile_number) {
var e = document.getElementById("number");
e.innerHTML = "";
e.appendChild(document.createTextNode(formatted_number));
};
</script>
And then instead of using:
<body onload="_googWcmGet(callback, '0800-123-4567')">
<span id="number">0800-123-4567</span> </body>
I'm using:
<body> <span id="number">0800-123-4567</span> <script type="text/javascript">
window.onload = _googWcmGet(callback, '0800-123-4567'); </script> </body>
It errors out with _googWcmGet being undefined. Think this is due to my lack of knowledge of JS/DOM stuff and that I need to cal _googWcmGet outside the body tag some other way?

How to display string length in javascript

I am new to javascript, and today i was trying my first example as shown below in the code section. I am using an editor called "Free Javascript Editor".
when I run the code, the browser starts and the text between the tags is displayed but the length of the string is never shown.
am I using it wrong?? please let me know how to do it correctly
lib
compile 'io.reactivex.rxjava2:rxjava:2.0.1'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
code:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<script>
var str = new string ("MyString");
str.length;
</script>
<h2>My First JavaScript</h2>
</body>
</html>
Use Onload event and put it inside js function.
<body onload="myFunction()">
<script>
function myFunction() {
var str = ("MyString");
var n = str.length;
document.getElementById("printlength").innerHTML = n;
}
</script>
<h2>My First JavaScript</h2>
<p id="printlength"></p>
</body>
Use document.createElement
var str = "MyString";
var p = document.createElement("p");
p.textContent = str.length;
document.body.appendChild(p);
Scripts are not rendered by the browser, only executed. You can, however, do something like this:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<h2>My First JavaScript</h2>
<p id="theLength"></p>
<script>
// No need to invoke the string constructor here.
var str = 'MyString';
// Find our placeholder element and set the textContent property.
document.getElementById('theLength').textContent = str.length;
</script>
</body>
</html>
It's good practice to put your script tags at the end of the body element - that way all of the HTML should render before the scripts are executed.
You should assign the length of your string to a variable. Then, you can show it.
<span id="stringLength"></span>
<script>
var str = "MyString";
var length = str.length;
document.getElementById('stringLength').textContent = 'Length: ' + length; // Show length in page
console.log('Length: ' + length); // Show length in console
alert('Length: ' + length); // Show length as alert
</script>
It must be String, not string. Code below works.
var str = new String ("MyString");
str.length;
Changed your code to this:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<script>
var str = "MyString";
console.log(str.length);
</script>
<h2>My First JavaScript</h2>
</body>
</html>
Then you must look in the developer console for the output, here is how:
Google Chrome
FireFox
Safari

actually creating a webpage with javascript

An extremely simple question but I am noob. I have been learning javascript and jquery for a while on jsfiddle, there everything works fine, building cool quizzes and all, but when I tried to actually create a directory, reference the jquery library and my javascript file, nothing works, even the below code, when saved as an HTML file doesn't work. I just paste it into notepad and save it as html, when I open it with it doesn'T work.
<html>
<head>
<title>webpage</title>
<script type="text/javascript">
window.onload = function() {
var myDiv = document.getElementById('#div');
myDiv.appendChild(document.createTextNode("Hi my name is Mehmetcan"));
}
</script>
</head>
<body>
<div id="myDiv"> </div>
</body>
</html>
Use this as starting point:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<title>webpage</title>
<script type="text/javascript">
$(document).ready(function () {
var myDiv = document.getElementById('myDiv');
myDiv.appendChild(document.createTextNode("Hi my name is Mehmetcan"));
});
</script>
</head>
<body>
<div id="myDiv"> </div>
</body>
Another approach that doesn't rely on JQuery but on pure, vanilla javascript.
<html>
<head>
<title>webpage</title>
<script type="text/javascript">
document.body.onload = loadSite;
function loadSite() {
var newDiv = document.createElement("span");
var newContent = document.createTextNode("Hi there and greetings!");
newDiv.appendChild(newContent);
myDiv.appendChild(newDiv);
}
</script>
</head>
<body>
<div id="myDiv"> </div>
</body>
</html>
You can find the full javascript sample as well as more information here, on the document.createElement MDN pages.
document.body.onload = addElement;
var my_div = null;
var newDiv = null;
function addElement () {
// create a new div element
// and give it some content
var newDiv = document.createElement("div");
var newContent = document.createTextNode("Hi there and greetings!");
newDiv.appendChild(newContent); //add the text node to the newly created div.
// add the newly created element and its content into the DOM
my_div = document.getElementById("org_div1");
document.body.insertBefore(newDiv, my_div);
}

can any one explain and provide the correct the code?

The HTML file has:
<html>
<head>
<title>title</title>
<script style="text/css" src=".\Scripts\CSS\tryc.css"></script>
<script style="text/javascript" src=".\Scripts\JavaScripts\Text8.js"></script>
</head>
<body id="body">
<h1 id="heading1">Coming Soon</h1>
<object id="circle-svg" width="1300" height="560" type="image/svg+xml" data=".\Scripts\svg\ulti.svg"></object>
</body>
</html>
The JavaScript has
window.onload = function () {
var as = document.getElementById("body");
var as1 = as.getElementById("heading1");
as1.style.color = "blue";
alert(as1);
alert("try");
};
The text does not turn blue.
getElementById must always be called from a document object.
var as = document.getElementById("body");
var as1 = as.getElementById("heading1");
var as1 = document.getElementById("heading1");
No nested context is needed, because IDs must be unique within the document.
And FWIW, you can use document.body instead of putting an ID on the body.
Oh, also you should use forward slashes instead of backslashes to get your script.
<script type="text/javascript" src="./Scripts/JavaScripts/Text8.js"></script>
I dont think you can use
as.getElementById();
Why dont you go directly with:
as = document.getElementById('heading1');
as.style.color = 'blue';

Categories