So I have a variable in my script var mystring = "123" and my web page look like this
<body>
<div id="footer">
123
</div> </body>
I need a script that checks if the variable is the same as the footer content and if is not, replace it.
Just like this :
a="123";
if a == html.content.from.footer then
do nothing;
else
replace html.content.from.footer with a;
There's no need to check if the values are equal, because if you replace a value with an equal value then there's no change anyway. So all you really need to do is replace the value. Something like this:
document.getElementById('footer').innerHTML = mystring;
Using jQuery, this is simple:
if($("#footer").html() !== mystring) {
$("#footer").html(mystring)
}
Without jQuery:
if(document.getElementById('footer').innerHTML !== mystring) {
document.getElementById('footer').innerHTML = mystring;
}
Here,
<script>
var mystring = "123";
var footer = document.getElementById("footer");
if(footer.innerHTML != mystring){
footer.innderHTML = mystring;
}
</script>
PS. I agree with David that you don't need to check if you know the string you want in the footer anyway. Just adding the script with the if block because you asked it that way. Hope this helps.
var myVar = '1234';
var element = document.getElementById('footer');
if(myVar != element.innerHTML) {
element.innerHTML = myVar;
}
Related
I have an assignment in school but I'm totally stuck.
My assignment:
Make a program that ask for a text and then write out the text several times. First with just one letter, then with two and so on. For example, if the user write "Thomas", your program should write out "T", "Th, "Tho, "Thom", and so on.
My hopeless attempt
I been trying to use "Substring" and a loop to make it work but I'm not sure I'm on the right path or not. Right now my code look like this:
<head>
<meta charset= "UTF-8"/>
<title> assignment14 - Johan </title>
<script type="text/javascript">
var text= test.length;
for (i=0;i< test.length;i++)
function printit()
{
var str = test;
var res = str.substring (i, 2);
document.getElementById("test").innerHTML = res;
}
</script>
</head>
<body>
<h1>Assignment 14</h1>
<form name="f1">
<input type="text" id="test" value="" />
<input type="button" value="Hämta" onclick="printit(document.getElementById('test'))" />
</form>
</body>
Just need some kind of hint If I'm going in the right direction or not, should I use some other functions? Very thankful for help.
You have to rewrite a script.When you want to extract one by one you can use substring(); function.
How to Call : StringObject.substring (StartPoint,endPoint);
Solution:
<script type="text/javascript">
function printit(){
var test=document.getElementById("test").value;
var text= test.length;
for (i=0;i<= text;i++)
{
var res = test.substring (i, 0);
document.write(res);
document.write("<br/>");
}
}
</script>
You are on the right way. substring(start,end) in javascript gives you the consecutive part of the string letters from start index to end. You just use it in a wrong way for your case. You have to call it like this:
substring(0,i)
You need to make few changes to your code:
1) use document.getElementById('test').value in printit function call at onclick as you have to send the value of the textbox instead of innerHTML.
2) Modify the printif function-
function printit(test)
{
document.getElementById('test').value=''; /*remove existing text from textbox*/
for (i=0;i< test.length;i++) {
var res = str.substring (0, i+1);
document.getElementById("test").value += ' '+res;
}
}
In printit function empty the text box and then append each substring to the existing text to get "T Th Tho Thom.." and so on
Hope this helps.
I don't use for-loop for this (whenever possible, I prefer functional style). Instead, I write a function that returns an array of substrings:
const substrings = string =>
Array.from(string).map((_, i) => string.slice(0, i + 1))
And here's a working codepen
Output several time using substring() method can be done as below, create a function which performs this task of extracting the user inputted string on button click using forloop and substring() method.
var intp = document.querySelector("input");
var btn = document.querySelector("button");
var dv = document.querySelector("div");
btn.onclick = function() {
var b = intp.value;
for (var i = 1; i <= b.length; i++) {
var c = b.substring(0, i);
dv.innerHTML += c + "<br/>";
}
}
div{
width:400px;
background:#111;
color:yellow;
}
<input type="text">
<button>Click</button>
<br/><br/>
<div></div>
You have used a correct way for doing this, but as one of user suggest the start and end value of substring() was not correct.
I would like to ask for your help in having a web site that uses the following javascript:
<html>
<head>
...
</head>
<body>
...
<script>
$(document).ready(function(){
var pathArray = window.location.pathname.split( '/' );
var secondLevelLocation = pathArray[0];
var newPathname = "";
for (i = 0; i < pathArray.length; i++) {
newPathname += "";
newPathname += pathArray[i];
}
var str = "asd fgh roof_material";
var res = str.match(newPathname);
if (res) {
document.getElementById("demo").innerHTML = res;
} else {
document.getElementById("demo").innerHTML = "Basic text";
}
});
</script>
<div id="demo"></div>
</body>
</html>
Such as my website address is: https://www.mywebsite.com/roof_material
I get a string in a variable (newPathname) which contains the text after the / sign, in this example: roof_material
The problem is:
I would like to find the value of this variable in a text and if you can find it then you can post it on the website. It's works if I put a text in a variable like in the script:
var str = "asd fgh roof_material";
But I would like to find the value of this variable (newPathname) in a separate html file, if it is possible like this:
The newPathname value such as: roof_material
In the separated .html file content:
<div id="protection_material">Line-X material</div>
<div id="roof_material">Roof materials</div>
<div id="pool_material">Swimming pools</div>
In this example I would like to find the roof_material ID in the .html file and get the content of the div: "Roof materials" and I would like to show this text on the page:
<div id="demo">Roof materials</div>
If it has positive match then show the content of the div in other cases, it will print a basic text like in the example: "Basic Text"
Could anyone help to make it happen?
#Terry thanks for your answer!
I think I found a simpler solution, but it's not perfect:
<script>
$(document).ready(function(){
var pathArray = window.location.href.split('=')[1];
var secondLevelLocation = pathArray[0];
var newPathname = "";
for (i = 0; i < pathArray.length; i++) {
newPathname += "";
newPathname += pathArray[i];
}
document.getElementById("demo").innerHTML = newPathname;
});
</script>
<div id="demo">Országosan</div>
If I type it in the browser such as: https://www.mywebsite.com/index then the text that will appear in #demo div is: "Országosan"
It's good, but if I type such as: https://www.mywebsite.com/index?id=Cserkeszőlő
then the result is good but character encoding does not work properly.
The result in the #demo div: Cserkesz%C5%91l%C5%91 , but I would like to show the correct encoded text like this: Cserkeszőlő
Can you give me a solution on this?
I am new to javascript so please forgive me if this is a simple answer. I cannot seem to find it. I have a small block of script that replaces text based on the content of the paragraph. Very easy. My questions is, why do I have to right out the entire reference twice? Does the variable not point to the same thing? Is there a simpler way?
This works:
<p id="name">Electric City</p>
<script type="text/javascript">
var name = document.getElementById("name").innerHTML;
if (name == "Electric City") {
document.getElementById("name").innerHTML = "Welcome!";
}
</script>
This doesn't:
<p id="name">Electric City</p>
<script type="text/javascript">
var name = document.getElementById("name").innerHTML;
if (name == "Electric City") {
name = "Welcome!";
}
</script>
Thank you!
var name = document.getElementById("name").innerHTML;
That line of code gets the value from your "name" element (using its innerHTML property) and copies it to the variable name. The name variable does not refer to the "name" element itself.
If you want to simplify your code, you could do something like this:
<script type="text/javascript">
var nameElement = document.getElementById("name");
if (nameElement.innerHTML == "Electric City") {
nameElement.innerHTML = "Welcome!";
}
</script>
In JavaScript, saying variable = value doesn't affect the thing that variable originally referred to. Saying variable.property = value does affect the thing that variable refers to.
So to simplify the code, do this:
var element = document.getElementById("name");
if (element.innerHTML == "Electric City") {
element.innerHTML = "Welcome!";
}
Example
Try this:
<script type="text/javascript">
var name = document.getElementById("name");
if (name.innerHTML == "Electric City") {
name.innerHTML = "Welcome!";
}
</script>
name is only holding the value and isn't referencing the actual element as a whole.
You need to grab the element THEN check and apply the innerHTML to it.
Try this:
var elem = document.getElementById("name");
if (elem.innerHTML == "Electric City") {
elem.innerHTML = "Welcome!";
}
The problem is that you had a reference to a string, not a reference to the object that holds the string. Since strings are immutable, setting a new value of a string variable just creates a whole new string and leaves the original (that was referred to my your element) untouched.
as simple as this
<p id="demo">Electric City</p>
<script>
var str = document.getElementById("demo").innerHTML;
var res = str.replace(/Electric City/gi," Welcome!");
document.getElementById("demo").innerHTML=res;
</script>
or
<script>
var str = document.getElementById("demo");
var res = str.innerHTML.replace(/Electric City/gi," Welcome!");
str.innerHTML=res;
</script>
I need to add an external javascript file to the <head> section of a website - one file when on the Staging server, and a different one for production.
So far I have this, but I get an error: 'return' outside of function
<script type="text/javascript">
var pathOrigin = window.location.origin;
var headtg = document.getElementsByTagName('head')[0];
if (!headtg) {
return;
}
var linktg = document.createElement('script');
if (pathOrigin.toLowerCase().indexOf("staging.server.com") >= 0) {
linktg.src = '/script-staging.js';
} else {
linktg.src = '/script-production.js';
}
headtg.appendChild(linktg);
</script>
What am I missing?
Thanks.
Return - Specifies the value to be returned by a function.
That means the error you got from the browser is correct. Your returnstatement is not part of a function, but of the global scope. You wil either have to skip using the return statement and use simple variable assingment like in #Azzy's answer, or encapsulate it in a function like so:
function getHead() {
var headtg = document.getElementsByTagName('head')[0];
if (typeof headtg === 'undefined') {
return; // will break the function
} else {
var linktg = document.createElement('script');
if (pathOrigin.toLowerCase().indexOf("staging.server.com") >= 0) {
linktg.src = '/script-staging.js';
} else {
linktg.src = '/script-production.js';
}
headtg.appendChild(linktg);
};
};
getHead(); // don't forget to initialize the function
//or you could do:
element.onload/onclick/on<whatever_event> = getHead();
To me it is also not clear what you want to return, unless you simply want to stop script execution; citing from MDN:
If the expression in return [expression] is omitted, undefined is returned instead.
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return
NB: Check this why it is safer to use the typeofstatement than a simple !mark to check if something exists: Check if object exists in JavaScript.
EDIT: For a very simple use case of the return statement, you can check out this fiddle I made which is basically a counter that will output an error when it reaches 100.
Where place this code? Are you sure that the path is correct?
Another method to add js file into head is this method:
<head>
....
<script type="text/javascript">
var pathOrigin = window.location.origin;
var path = "";
if (pathOrigin.toLowerCase().indexOf("staging.server.com") >= 0) {
path = '/script-staging.js';
} else {
path = '/script-production.js';
}
document.write( '<script type="text/javascript" src="' + path + '"><\/script>' );
</script>
.....
</head>
<html>
<head>
<script type='text/javascript'>
var path = window.location.origin
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
if (path == 'local'){
fileref.setAttribute("src", 'file:///D:/JS/jquery.js')
}
else{
fileref.setAttribute("src", 'file:///D:/JS/jquery.js')
}
document.getElementsByTagName("head")[0].appendChild(fileref)
//list all the js loaded dynamically
var scripts = document.getElementsByTagName('script');
console.log(scripts);
</script>
</head>
<body>
<p>test</p>
</body>
</html>
To load script dynamically, you can try out this..
The javascript error "return statement outside of function" means you've created a code fragment that is not allowed to exist outside of a function definition.
current code (not working):
/^script\s*type=\"text\/javascript/i.test(tagName)
/<script\stype\=\"text\/javascript\">/i
Regular expressions and HTML — bad things. How regex will work for next examples (don't forget about single and double quotes)?
<script type="text/javascript">
<script language="JavaScript" type="text/javascript">
<script type="text/javascript" language="JavaScript">
<script class="myJS" type="text/javascript">
<script type="text/javascript" class="myJS" >
Instead of regular expressions, I suggest to use a function like this:
function attr_in_str(str, tag, attr) {
var div = document.createElement('div');
div.innerHTML = str;
var elems = div.getElementsByTagName(tag);
for (var i = 0; i < elems.length; i++) {
if (elems[i].type.toLowerCase() == attr.toLowerCase()) {
return true;
}
}
return false;
}
Then use it:
var str = 'This is my HTML <script type="text/javascript"></script>';
var result = attr_in_str(str, 'script', 'text/javascript');
Assuming that you are aware of all the assumption when you use regex to process HTML.
You can just remove the ^ in your current code, since it matches the start of the string.
EDIT
Number of spaces should be at least 1, so your should change the * after \s into +
I'm not a big fan of regex, so I'd do this:
var temp = document.createElement('div');
temp.innerHTML = '<script type="text/html"></script>';
var type = temp.childNodes[0].getAttribute('type');
if (type == 'text/javascript') {
// ...
}
If you were using jQuery, it would be way easier:
if ($('<script type="text/html"></script>').prop('type') == 'text/javascript') {
// ...
}
To account for the 'type' appearing anywhere within the script tag, and multiple versions of quotes, use:
/<script.*?type\s*=\s*.text\/javascript./i
You could tighten it up by specifying all quote alternatives instead of '.'.