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

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);

Related

Passing HTML value to embedded script

So I have a HTML file with an embedded script. A Java application sends a value to this HTML file. Now I wonder how to pass this value from the HTML down to the script. Is this even possible?
Here is the simplified HTML file with my approach:
<html>
<body>
<div id="test">
[VALUE_FROM_BACKEND] // prints "let valueFromBackend = 1234"
</div>
<script>
console.log(document.getElementById('test').value);
// should return: let valueFromBackend = 1234;
// actually returns: undefined
</script>
</body>
</html>
Unfortunately, I can't pass the value from the Java application directly to the script. I got the above approach from here, but this doesn't work.
Other solutions only focus on getting values from remote HTML pages, declaring the HTML files's source in the script tag. But since it is an embedded script here, this also seems not to work.
Does anyone know how to deal with the situation? Help will be much appreciated.
Only HTML input elements have a value in javascript. A div cannot have a value, which is why your code returns undefined.
To access the text inside a regular HTML element, such as a div, use element.innerText instead.
Here is a working code snippet you can try out:
console.log(document.getElementById('test').innerText);
<div id="test">
let valueFromBackend = 1234
</div>
As you want to get value of a div element, so the syntax is:
document.getElementById('test').innerHTML
Remember that getElementById().value works for input and use getElementById().innerHTML for elements like div

Uncaught ReferenceError: var is not defined

I have two textarea which starts on empty value.
Then when I fill the first textarea with id "postcrudo" I want that the next textarea (with id "posthecho") getthe same value as the first, and also show the same. Like a two way binding, like AngularJS, but only with JavaScript and jQuery.
This is the JS:
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
$("#postcrudo").val(function(){
algo = this;
});
postHecho = postCrudo;
console.log("OK!");
});
});
</script>
and this the HTML:
<body>
<div style="width:700px;float:left;">
<p>Post crudo:</p>
<p><textarea cols="100" maxlength="99999" name="postCrudo" id="postcrudo" rows="60"></textarea></p>
</div>
<div style="width:700px;float:left;">
<p>Post pasado:</p>
<p><textarea cols="100" maxlength="99999" name="postHecho" id="posthecho" rows="60"></textarea></p>
</div>
<div style="clear:both;"></div>
<p><input type="submit" value="submit" id="submit" /></p>
</body>
The error in Chrome console is:
Uncaught ReferenceError: postCrudo is not defined
Is this what you want?
https://jsfiddle.net/a4nmto6t/1/
Just get the value of the first textarea and change the value of the second to that:
$(document).ready(function(){
$("#submit").click(function(){
var postCrudoVal = $("#postcrudo").val();
$("#posthecho").val(postCrudoVal);
console.log("OK!");
});
});
Neither postHecho nor postCrudo are declared (by you**), and even if they were, assigning one of them to the other does not do what you want. You have to assign the value of the first textarea to the value of the second textarea using (in this case) jQuery selectors, because they ARE the ones referencing the DOM elements (the textareas).
** Elements that have an id are set as global 'variables' by default, but you shouldn't use them; it is instead suggested that you either use the DOM API to find elements or use jQuery (which uses the DOM API behind the scenes).
There is no declaration of postCrudo so it is undefined. Also why would you want to try and do this yourself instead using something like AngularJS to handle data bindings. You are essentially doing more work for no reason. Plus you have to handle all aspects of 2 way data binding manually. To me there is smarter ways to do this.
Your element id postcrudo is all lowercase. postCrudo is indeed not defined
This linepostHecho = postCrudo; makes no sense, I think you're trying to do this:
$('#posthecho').val($('#postcrudo').val())
JavaScript syntax is case sensitive.
`postHecho = postCrudo;`
Should be:
`postHecho = postcrudo;`

html assigning value to input text using javascript does not work

I am new to programming and I have a small problem
I have a form named "fr" with an input text box named "in" and a variable "n" with the value of "my text"
this is my code what I have:
<html>
<head>
<script LANGUAGE="JavaScript">
var n = "my text";
document.fr.in.value = n;
</script>
</head>
<body>
<form name="fr">
<input name="in" size="3">
</form>
</body>
</html>
but somehow input "in" does not show the text "my text"
I have been browsing the internet but I couldn't find any solution which works..
everything what I try does not work.
I think I am doing something very simple wrong.
please help me.
document.fr does not exist yet at time of invocation; hence, everything following it doesn't exist either, so it throws a TypeError
TypeError: Cannot read property 'in' of undefined
To fix this, move your code to be invoked after the nodes exist, using your favourite method
window.addEventListener('load', function () {
var n = "my text";
document.fr.in.value = n;
});
I'll further note that;
The preferred way to look up an Element is to give it an id attribute and use document.getElementById. An id must be unique.
Using the language attribute of <script> is depreciated, if you want to specify the language, use the type attribute type="text/javascript" or type="application/javascript"
Opening the Console when a script is not working as expected will often show you the cause immediately. This is usually done with F12.
You should init the script after the form is defined, as explained by Paul S. in his answer. So you may do,
<html>
<head>
</head>
<body>
<form name="fr">
<input name="in" size="3">
</form>
<script type="text/javascript">
var n = "my text";
document.forms.fr.in.value = n;
</script>
</body>
</html>
This would run the script after the form is defined. Or put this code in some function, and instantiate the function after the form is defined(i.e. loaded).
As Paul pointed out you should only try to get a hold of page elements when you are certain that the element you are interested has already been loaded. So in this case you can set the value of the input field by running your code when the page has fully loaded and by getting a reference to the input like this:
window.addEventListener("load", function () {
var n = "my text";
var myInput = document.getElementsByName("in");
myInput[0].value = n;
});
Note, because getElementsByName() returns an array, you will have to use [0], to get the first element.

Javascript inline output

In javascript suppose you have this piece of code:
<div>
<script type="text/javascript">var output = 'abcdefg';</script>
</div>
Is there any way to simply "echo" (using PHP terminology) the contents of output into #test? That is, to output a string inline, assuming you have no standard way of traversing or selecting from the DOM?
document.write("..."); does write the contents of output, but in doing so, it replaces the entire document with the output.
The solution I'm looking for should act the same way a PHP echo would: write the output into the document inline.
You'd have to use document.write [docs]:
<div id="test">
<script type="text/javascript">document.write('abcdefg');</script>
</div>
DEMO
With the caveat that it does not work in XHTML documents. See the documentation for more details.
"Kosher" code aside, yes.
document.write()
In standards-based browsers:
document.getElementByID("test").textContent = output;
For broader support, you could use text in jQuery (or the equivalent method if your library of choice):
$('#test').text(output);
If your code is in the div, then document.write('abcdefg') is the proper choice for inserting something inline at the point of execution.
Or, if your code is not inside the div, you can do this:
<div id="test">
</div>
<script type="text/javascript">
var output = 'abcdefg';
document.getElementById("test").innerHTML = output;
</script>
You will have to make sure that your code runs AFTER the page is loaded and the div is present.
You could write something like:
<div id="test">
<script>
document.getElementById('test').innerHTML = "stuff";
//this line only changes content in the div with id="test", not the whole dom
</script>
</div>
But you should avoid putting a script inside a div because it may be overwritten.
I know this is an old question but if anybody is still looking then here is a handy function that does the job.
function echo(text)
{
document.body.appendChild(document.createElement("div")).appendChild(document.createTextNode(text));
}
console.log()
http://getfirebug.com/logging
also supported in chrome and ie 9.. watch out for backwards compatibly it will get you ie8 and down i think...

Can a JavaScript variable be used in plain HTML?

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 }}.

Categories

Resources