Javascript inline output - javascript

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

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

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

write html in javascript without documet.write

<script >
for(i=0;i<=9;i++)
{
</script>
<input type="button" value="1"/>
<script type="text/javascript">
}
</script>
This puts button only 1 time if I use document.write it prints 10 times why ?
JavaScript does not behave in the same way PHP does. Whatever you place between the <script> tags is a script in and of itself.
So you have two separate scripts:
This:
for(i=0;i<=9;i++)
{
and this one:
}
Imagine what would happen if you placed these two scripts into two separate files? That's right, both would fail because of syntax errors. If you take a look at the console you'll see what errors I'm talking about.
If you want to print 10 buttons do something like this:
<div id="mainDiv">
</div>
<script>
var mainDiv = document.getElementById('mainDiv');
for(var i=0; i<10; i++){
mainDiv.innerHtml += "<input type='button' value='1'>";
}
</script>
These script tags are separate scripts. You can use functions or variables defined in the first one, but you cannot have a for loop spanning both.
The html in between is not in the script either. It looks like your trying to use script tags as if they're <?php?> ones.
Alternatives to document.write, is setting the contents of an element's innerHTML or adding an element to the DOM:
for(i=1;i<10;i++){
var btn = document.createElement("button");
document.body.appendChild(btn);
}
HTML is not a template engine as PHP so you can't separate a code block into multiple script tags. Each code block must be placed entirely in a <script></script> tag pair.
If your purpose is generate 10 buttons with Javascript, please go with document.write option
you are looking for some sort of server side templating. remember javascript runs on the client.

How can I use CSS to show and hide multiple elements at once?

I found this article that looked like exactly what I wanted, but I can't seem to get it to work at all. Since it is well over a year old, I thought perhaps something may have changed, or that there might be a simpler way to do it by now.
That is to say, I cannot get the method I linked above to work. I copied and pasted exactly, and used <body onLoad="javascript_needed()"> because I wasn't sure where $(document).ready(function ()... was supposed to go. I am, sadly, quite unfamiliar with Javascript.
Use something like this;
<script>
$(document).ready(function(){
//Code goes in here.
});
</script>
Don't forget to load the jQuery library at the same time from http://jquery.com/
Also, you are going to want to read up on selectors.
Using $("#myElement") will select elements that have an id of "myElement".
Using $(".myElement") will select elements that have a class of "myElement".
So;
<div class="hideMe">Content</div>
<div class="hideMe">Content</div>
<div class="hideMe">Content</div>
<div class="doNotHideMe">Content</div>
<input type="button" class="ClickMe" value="click me"/>
<script>
$(function(){
$(".ClickMe").click(function(){
$(".hideMe").hide(250);
});
});
</script>
edit
If you want to link to the jquery library online then use;
<script src="http://code.jquery.com/jquery-1.6.1.min.js" type="text/javascript"></script>
If you download the library and insert the js file into your project then use;
<script src="/yourPathToTheLibrary/jquery-1.6.1.min.js" type="text/javascript"></script>
The $ syntax is all part of jQuery. If you wish to use jQuery then somewhere in your code, use a script tag as in your post:
<script>
$(function() {
$('.selector').hide(250);
});
</script>
If you want pure JavaScript, then there is a little more overhead. Not including the document ready stuff (which can be a lot of extra code to do it right...See example: here).
<script>
elements = document.querySelectorAll('.selector');
for(int i=0,len=elements.length;i<len;++i) {
elements[i].style.display = 'none';
}
</script>
You can put that in a function if you would like. To show the elements set the display attribute to ''.

Playframework: Elegant way to pass values to javascript

Does anyone have an elegant solution to pass server values to javascript (that is not inline) in playframework? just like ${x} or &{'x'} inside html
Currently I can think of
<script type="text/javascript">
var x= ${x};
</script>
<script src="/public/javascripts/jsThatUsesX.js" type="text/javascript" ></script>
I'm thinking there is a better solution from play
It's not pretty, but that's the way I always end up doing it.
If the values that you're passing to JavaScript describe something in the DOM, you might consider using HTML 5 data attributes to place that information in the HTML. Then you can retrieve it with getAttribute. e.g. If your page is a blog post and you need to store the post ID you could use
<div class="post" data-post-id="77">
...
</div>
That way the data is separated out from the logic and you don't need to inline any JavaScript. You could also use a hidden form field.
What's wrong with that? I found myself doing things like
<script>
var trades = [${_trades.collect {models.Trade t -> t.price}.join(", ")}];
// ...
</script>
I like it the groovy way ;)

Categories

Resources