Can a JavaScript variable be used in plain HTML? - javascript

What I mean is, can a variable/array declared and initialized be used in HTML, outside the <script>-tags? Fx.
<script type="text/javascript">
var foo = array('placeholder1', 'placeholder2');
</script>
<body>
<p><!--access the variable here-->foo[0]</p>
</body>
How do you access the variable/array in this case? like this:
<p><script type="text/javascript">document.print(foo[0])</script></p>
??

Two ways to do this. This is the better one:
<script type="text/javascript">
// make sure to do this onLoad, for example jQuery's $()
var foo = array('placeholder1', 'placeholder2');
document.getElementById("fooHolder").innerHTML = foo.toString();
</script>
...
<p id="fooHolder"></p>
Or you could do it this way (which, as Marcel points out, doesn't work in XHTML and really shouldn't be used anyway):
<p><script type="text/javascript">document.write(foo)</script></p>

You can do something like this:
<script>
var str = 'hello there';
document.getElementById('para').innerHTML = str;
</script>
where an element has the specified id:
<p id="para"></p>

you simply cannot access javascript variable outside of the script tag, it is because,
Html does not recognise any variable it just renders the supported HTML elements
variables are used to store the temporary variables, that is for dynamic data, if you want something more dynamic then you can use PHP for that.

Unnecessarily verbose, but using standard DOM methods.
<script>
window.onload = function(){
// you do not need to initialize like this, but I like to
var bar1 = new String('placeholder1');
var bar2 = new String('placeholder2');
var foo = new Array();
// populate the Array with our Strings
foo.push(bar1);
foo.push(bar2);
// create an array containing all the p tags on the page
// (which is this case is only one, would be better to assign an id)
pArray = document.getElementsByTagName('p');
// create a text node in the document, this is the proper DOM method
bar1TextNode = document.createTextNode(foo[0].toString());
// append our new text node to the element in question
pArray[0].appendChild(bar1TextNode);
};
</script>
<body>
<p></p>
</body>

That's the only direct way you'll access it elsewhere in your page. By opening another script tag and printing it.
You can also use methods such as innerHTML to put the value somewhere.

I don't think you can access the javascript from html but you can set the innerhtml of a dom object through javascript so you may want to go the other way around. First google search I found so I cant promise its good but it has a quick sample.
http://www.tizag.com/javascriptT/javascript-innerHTML.php

You can even you AngularJS expression.
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.framework= "AngularJS";
});
</script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>I want to use variables directly in HTML using: {{ framework }}</p>
</div>
</body>
</html>
The above code will print out "I want to use variables directly in HTML using: AngularJS".You can use braces to write AngularJS expression. For example: {{ expression }}.

Related

Getting Wix HTML element into iFrame variable

I have a wix webpage with an HTML element on the page. I need to get the text of that element into my iFrame that contains javascript. I'd like to store that text of the html element as a variable in my iFrame javascript.
When I try the code below, my iFrame variable prints as 'undefined' in the web console.
<script>
var myElement = document.getElementById("#text15").text;
console.log(myElement);
</script>
The JavaScript function getElementById() receives as parameter the string of the id value it should search in the DOM. So, you are searching for this:
<div id="#text15"></div>
To find this element in the DOM:
<div id="text15"></div>
You could either do:
var myElement = document.getElementById("text15").innerText;
Or if you like using the hash symbol when referencing elements from the DOM, you can also try:
var myElement = document.querySelector("#text15").innerText;
Both work the same way. And also, use innerText which references as the content inside the tag. The text property of the DOM element returned by JavaScript does not exist.
Note: You should not reference your DOM elements right in a <script> tag. Since most likely the elements won't be ready by the time you call them.
Try:
<script>
window.onload = function() {
var myElement = document.getElementById("#text15").innerText;
console.log(myElement);
}
</script>
Look at an example of both ways:
var text1=document.querySelector("#myElement").innerText;
console.log(text1);
var text2=document.getElementById("myElement").innerText;
console.log(text2);
<div id="myElement">Hello!</div>
using jquery
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#inPut').click(function() {
var myElement =
$('#text15').val();
console.log(myElement);
});
});
</script>
</head>
<body>
<br>
<input type='text' id='text15'>
<button id='inPut'>Write to console</button>
<br>
</div>
</body>
</html>

Difficulty with using HTML DOM .createElement(), .setAttributeNode(), and .appendChild() methods

I'm learning how to develop a dynamic webpage and am trying to use HTML DOM to add JS objects but nothing is appearing after several troubleshooting attempts.
I've tried using .createAttribute() instead of .setAttribute() and have carefully read the descriptions of all the methods to make sure I was using them correctly.
<html>
<body>
<div id="greeting_section">
</div>
<script>
let greeting_post = document.createElement("P");
greeting_post = document.setAttributeNode("id","post");
let greeting_post_text = document.createTextNode("howdy howdy");
greeting_post.appendChild(greeting_post_text);
document.getElementById("greeting_section").appendChild(greeting_post);
</script>
</body>
</html>
I expect it to output "howdy howdy" but nothing appears in my Firefox browser.
It looks like you're overwriting greeting_post. Also, you might just be meaning to use setAttribute instead of setAttributeNode. See below for a working example.
let greeting_post = document.createElement("P");
greeting_post.setAttribute("id","post");
let greeting_post_text = document.createTextNode("howdy howdy");
greeting_post.appendChild(greeting_post_text);
document.getElementById("greeting_section").appendChild(greeting_post);
<html>
<body>
<div id="greeting_section">
</div>
</body>
</html>
First: When I ran your code the browser console showed this error
Uncaught TypeError: document.setAttributeNode is not a function
That's the first thing you should do when your code doesn't work, Take a look at the browser console.
Second: in your code greeting_post = document.setAttributeNode("id","post"); you are trying to add id="post" to greeting_post variable which is the p tag put you do it wrong, Your code means change the variable greeting_post to a new value document.setAttributeNode("id","post"); which mean Set attribute id="post" to the document.
So, instead of your code, The correct code should go like this:
greeting_post.setAttribute("id","post");
In English this is mean, select greeting_post and set it's attribute to id="post"
So finale, The complete code should be like this:
let greeting_post = document.createElement("P"),
greeting_post_text = document.createTextNode("howdy howdy");
greeting_post.setAttribute("id","post");
greeting_post.appendChild(greeting_post_text);
document.getElementById("greeting_section").appendChild(greeting_post);

How to filter/parse string of html templates with plain javascript?

I have a string of html templates, each wrapped in script tag with id-s.
Example templates string:
<script id="id1"> some html </script>
<script id="id2"> some other html </script>
I want to find template in this string with specified id and get html template without wrapper script tag.
Here is jquery approach to this problem that works:
var template = $(templates).filter("#id1").html();
Unfortunately I need to do the same thing in plain javascript, but I can't find a simple solution to this problem. How can I do this without jquery?
var template = `<script id='id1' src="" /><script id='id2' src="" / >`;
var div = document.createElement('div');
div.innerHTML = template;
var filterElement = div.querySelectorAll("#id1");
console.log(filterElement[0]);
With javascript, you can get a a DOM node by id using
document.getElementById("ID_GOES_HERE")
So, in your case, I would try something like
let tmplt = document.getElementById("id1").innerHTML;
or
let tmplt = document.getElementById("id1").innerText;
Read more about dom elements here.
Also, on a side note, let is probably better to use then var, as it has better scoping, but in the above code I wrote, let could be substituted with var
I suppose you can do this by using Regular Expressions.
This website may help you to find the right one.

Calling JavaScript function into a P tag

I would like to call the following javaScript function so it gets outputted to a HTML P tag, but am not sure how to do this without explicitly calling the function in the HTML file.
I do not want to do this...
<p class="showcode">
<script type="text/javascript">
wise_words();
</script>
</p>
I would like to keep the javaScript code all in one js file.
I have tried it this way but this does not seem to work...
document.getElementById("showcode").innerHTML = wise_words();
I would really appreciate any help as to what I am doing wrong.
Here is my code... http://codepen.io/anon/pen/qfLdE I would like to have the generated text get outputted inside the grey box.
You should call the function in an onload handler, so that it is executed after the DOM has been constructed:
window.onload = function() {
document.getElementById("showcode").innerHTML = wise_words();
}
Another problem is that your wise_words() function is using document.write (please don't use document.write) instead of returning a value. You need to return a value:
var retText = wiseText[nextVal][0];
nextVal += 1;
writeCookie("wisewords", nextVal.toString(), 33);
return retText;
Try following using Jquery:
$(".showcode").html(wise_words());
NOTE: Assuming your function returns the HTML/text.
<p class="showcode">
<script type="text/javascript">
document.write(wise_words());
</script>
</p>
or:
<body onload="document.getElementById('showcode').innerHTML = wise_words()">
<p id="showcode">
</p>
</body>
(note id instead of class).

Override existing HTML Element attribute and property with Javascript

I was wondering if its possible to override existing HTML Element attribute and property accessors (getters and setters) with Javascript so that when html is rendered by browser all the assignments to certain attributes in the html code are preprocessed with custom functionality.
Here is an example :
<html>
<head>
<script>
// JS code would go here which would override default behavior
// for example if I wanted to reformat id="name" so its actually
// registered as id="pre_name" once browser renders the html
</script>
</head>
<body>
<!-- here we are assigning the 'name' to id , but behind the scene we really want it to be 'pre_name' -->
<div id="name"></div>
<script>
// when we try to access the id it would actually match the overwritten one
console.log(document.body.children[0].id) // would output pre_name
</script>
</body>
</html>
Is something like that possible and how?
I know that I can traverse the dom after it's rendered and change all of the ids, but I am wondering if its possible to intercept the assignment of properties and attributes and do it at that level before browser even renders the html.
Example I presented is just made up one to present the problem and make is simple to understand.
Thanks
Unfortunately this is not possible, you can only modify the name element after it is loaded.
So it would be something like this:
<body>
<!-- here we are assigning the 'name' to id , but behind the scene we really want it to be 'pre_name' -->
<div id="name"></div>
<script>
// right after
document.getElementById('name').id = 'pre_name';
</script>
<script>
// when we try to access the id it would actually match the overwritten one
console.log(document.body.children[0].id) // would output pre_name
</script>
</body>
or even
<body>
<!-- here we are assigning the 'name' to id , but behind the scene we really want it to be 'pre_name' -->
<div id="name"></div>
<script>
// or here
document.getElementById('name').id = 'pre_name';
// when we try to access the id it would actually match the overwritten one
console.log(document.body.children[0].id) // would output pre_name
</script>
</body>
You can use html data-* attributes for second value like;
<div id="name" data-second="pre_name"></div>
And then you can use,
var div = document.getElementById('name');
div.getAttribute("data-second");

Categories

Resources