I have created javascript program in that I have created div tag in body and prompt in order to accept text from user after that I have created div and want to add prompt text to div.The new div should be display before already created one and for that I have used insertBefore(). I tried to get the value in console and I am getting values in console. but my program is not working as per expectation.
code:
<!DOCTYPE html>
<html>
<head>
<title>trail</title>
<meta charset="utf-8">
<style type="text/css">
.pink{
background-color: pink;
}
.green{
background-color: #71e887;
}
</style>
<script type="text/javascript">
var movieText = prompt("What movie do you like?");
var newDiv = document.createElement("div");
parent = newDiv.parentNode;
newDiv.className = "green";
var text = document.createTextNode(movieText + " is a good movie");
newDiv.innerHTML = text;
newDiv.appendChild(text);
var beforeMe = document.getElementById("div1");
document.body.insertBefore(newDiv, beforeMe);
</script>
</head>
<body>
<br>
<div class="pink" id = "div1">
I love watching movies <br/>
This is one of my favorite movie:
</div>
</body>
</html>
my output:
[![enter image description here][1]][1]
expected output:
[![enter image description here][2]][2]
As #pari mention, you are inserting a text node objet using innerHTML. This function will performance a .toString() to the text node. That is way you are receiving the output [object text]. If you are required to use innerHTML then just go with .innerHTML(movieText + " is a good movie")
Or you can use the text node like this :
var textNode = document.createTextNode(movieText + " is a good movie");
newDiv.appendChild(textNode);
but do not use both at the same time.
Related
I'm new to javascript and programming, and I am trying to create a webpage where the user can input the data on the page, and then I wrap it around HTML code to create an HTML template. I've tried using a couple methods but the document.write() command seems to be working for what I need. However, I'm trying to add the HTML tags around the input text and not getting a usable format.Full code below:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta charset="utf-8"/>
</head>
<body>
<h1>Title<input type="textarea" id="top_field" value="" style="width:100px; height:30px"></h1>
<br/>
<h2>Position/Proposal<input type="textarea" id="subtitle_field" value="" style="width:100px; height:30px"></h2>
<br/>
<p>Body Text: <input type="textarea" id="field1" value="" style="width:100px; height:30px"></p><br/>
<button id="sub_button" type="button" onclick="myFunction()">Copy</button>
<div id="full_code" hidden>
<p id="must_have" value='text'><!DOCTYPE> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta charset="utf-8"/><br></head>
</p>
<p id="less_than"><</p>
<p id="more_than">></p>
</div>
<script>
function myFunction() {
//const html_array = ["<!DOCTYPE>", "<html>", "<head>", "<meta name="viewport" content="width=device-width, initial-scale=1"/>", "<meta charset="utf-8"/>", "</head>"];
if(document.getElementById("field1").value != "" || document.getElementById("top_field").value != "" || document.getElementById("subtitle_field").value != ""){
let p_elem = document.getElementById("less_than").innerText + "p" + document.getElementById("more_than").innerText;
let pend = document.getElementById("less_than").innerHTML + "/p" + document.getElementById("more_than").innerHTML;
let body = document.getElementById("less_than").innerHTML + "body" + document.getElementById("more_than").innerHTML;
let bodyend = document.getElementById("less_than").innerHTML + "/body" + document.getElementById("more_than").innerHTML;
var top_text = document.getElementById("must_have").innerText;
var newParagraph2 = document.createElement("p"); //creates a new paragraph element
var newText2 = document.createTextNode(top_text); //creates text along with output to be displayed
newParagraph2.appendChild(newText2); //created text is appended to the paragraph element created
document.body.appendChild(newParagraph2); // created paragraph and text along with output is appended to the document body
var main_text = document.getElementById("field1").value;
var newParagraph = document.createElement("p"); //creates a new paragraph element
var newText = document.createTextNode(main_text); //creates text along with output to be displayed
newParagraph.appendChild(newText); //created text is appended to the paragraph element created
document.body.appendChild(newParagraph); // created paragraph and text along with output is appended to the document body*/
var title_text = document.getElementById("top_field").value;
var newParagraph3 = document.createElement("p"); //creates a new paragraph element
var newText3 = document.createTextNode(title_text); //creates text along with output to be displayed
newParagraph3.appendChild(newText3); //created text is appended to the paragraph element created
document.body.appendChild(newParagraph3); // created paragraph and text along with output is appended to the document body
var less_symbol = document.getElementById("less_than").value;
var newParagraph4 = document.createElement("p"); //creates a new paragraph element
var newSymbol = document.createTextNode(less_symbol); //creates text along with output to be displayed
newParagraph4.appendChild(newSymbol); //created text is appended to the paragraph element created
document.body.appendChild(newParagraph4); // created paragraph and text along with output is appended to the document body*/
document.writeIn(newParagraph2.innerText); //
}
else{
document.write("No text");
}
}
</script>
</body>
</html>
By now I'm able to read the text input and output in the same page below, but not able to add anything around the appended child or make the original tags above appear vertically. If someone can lead me in the right direction on method I should be using I would greatly appreciate it.
I would suggest NOT writing html strings with document.write. Instead, you can use createElement and appendChild to create html tags and add them to the page. It's much more readable and less likely to cause syntax errors in your html tags.
For example, to create a div that contains text from your inputfield:
let fieldValue = document.getElementById("myfield").value
let div = document.createElement("div")
div.innerHTML = fieldValue
document.body.appendChild(div)
Hope this generic example points you in the right direction!
I am trying to make a single button which copies text to the clipboard, but I am am having trouble. It is copying the wrong thing.
Essentially, I have a variable called my_fav_food. Then I have a button called My Fav Food. When I click this button, it calls the function copying_function and parses in the my_fav_food variable into the function. Then the function automatically copies the text to the clipboard.
<!DOCTYPE html>
<html>
<body>
<script>
var my_fav_food = "My fav food is pizza"
</script>
<button onclick="copying_function(my_fav_food)">My Fav Food</button>
<script>
function copying_function(string) {
string.select();
document.execCommand("string");
}
</script>
</body>
</html>
You need to create a DOM element and set the string to it then do the selection programmically. As you're not appending the element to the DOM, it will not be visible in the view.
<!DOCTYPE html>
<html>
<body>
<script>
var my_fav_food = "My fav food is pizza";
</script>
<button onclick="copying_function(my_fav_food)">My Fav Food</button>
<script>
function copying_function(string) {
// string.select();
const el = document.createElement('textarea');
el.value = string;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
console.log("The data copied successfully! press `ctrl+v` to see output");
document.body.removeChild(el);
}
</script>
</body>
</html>
The select() method can only be used to select the contents of a text field. You cannot use it the way you are using it now.
You could try: https://clipboardjs.com/
Or you might try a hack to put the text in a hidden text area (I don't guarantee this would work)
This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 4 years ago.
I am trying to change the text displayed by a div from 'hello' to 'hey' on click using innerHTML. I know my function is executed and the innerHTML is changed because I get an alert on click displaying 'hey', but on my webpage and in inspector the 'text' element's contents remain as 'hello'.
What is going on here?
code:
<html>
<head>
<script type="text/javascript">
function changehtml() {
var text = document.getElementsByClassName('text');
text.innerHTML = 'hey';
alert(text.innerHTML)
}
</script>
</head>
<body>
<div class='text' onclick='changehtml()'>
hello
</div>
</body>
</html>
Get elements by class returns an array of elements if you just want to change the one div give it and id and getElementById.
If you want to change multiple divs with that class the second snippet loops through the divs with that class and changes all of their texts.
function changehtml() {
var text = document.getElementById('x');
text.innerHTML = 'hey';
alert(text.innerHTML)
}
<html>
<head>
</head>
<body>
<div id="x" class='text' onclick='changehtml()'>
hello
</div>
</body>
</html>
function changehtml() {
var text = document.getElementsByClassName('text');
for (let i = 0; i < text.length; i++) {
text[i].innerHTML = 'hey';
}
}
<html>
<head>
</head>
<body>
<div class='text' onclick='changehtml()'>
hello
</div>
</body>
</html>
document.getElementsByClassName('text') gives you collection of nodes. So, you;ll have to loop through them to get each node. Or for this example you can use
document.getElementsByClassName('text')[0];
Or
document.querySelector('.text')
This will give you the first node with class name of text.
And make it your habit to check your console for errors, you'll probably be getting one
I am trying to automatically create an option menu (using HTML and JavaScript) based on the contents of a text file. What I would like is for each option in the menu to be a line in the text document.
Here is the JavaScript:
function get_parameters() {
alert("get_parameters() called"); // these alerts are just to tell me if that section of the code runs
var freader = new FileReader();
var text = "start";
freader.onload = function(e) {
text = freader.result;
alert('file has been read');
}
freader.onerror = function(e) {
alert('freader encountered an error')
}
freader.readAsText('./test.txt', "ISO-8859-1");
var div = document.getElementById('bottom_pane_options');
div.innerHTML = div.innerHTML + text;
}
With this code, all I'm trying to accomplish is reading the file and printing to the div "bottom_pane_options" but I can't find any reason why it doesn't work. If my way isn't the most efficient, could you please give me code that would work?
Thanks.
--EDIT--
Here is the HTML
<!DOCTYPE html>
<html>
<head>
<title>Culminating</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCJnj2nWoM86eU8Bq2G4lSNz3udIkZT4YY&sensor=false">
</script>
<script>
// Calling the Google Maps API
</script>
</head>
<body>
<div class="content">
<div id="googleMap"></div>
<div id="right_pane_results">hi</div>
<div id="bottom_pane_options">
<button onclick="get_parameters()">Try It</button>
</div>
</div>
</body>
<script type="text/javascript" src="./javascript.js"></script>
</html>
You need to set the <div> text in the callback instead of right after you start loading:
freader.onload = function(e) {
text = freader.result;
/*************
** TO HERE **
************/
alert('file has been read');
}
/* MOVE THIS */
var div = document.getElementById('bottom_pane_options');
div.innerHTML = div.innerHTML + text;
/*************/
Because the file was not read yet when you are runing div.innerHTML = div.innerHTML + text;.
That's why there are callbacks.
See https://developer.mozilla.org/en-US/docs/Web/API/FileReader :
The FileReader object lets web applications asynchronously read the
contents of files [...]
Use this instead :
freader.onload = function(e) {
text = freader.result;
var div = document.getElementById('bottom_pane_options');
div.innerHTML = div.innerHTML + text;
alert('file has been read');
}
freader.onerror = function(e) {
alert('freader encountered an error')
}
freader.readAsText('./test.txt', "ISO-8859-1");
Hi all i want to document.write a hyperlink image inside getjson i tried the following but it doesnt work. could you guys tell me what is wrong with my document write?
<script>
$.getJSON('http://anyorigin.com/get?url=http://www.somesite.com/handelit.ashx&callback=?', function(data){
var siteContents = data.contents;
//writes to textarea
document.myform.outputtext.value = siteContents ;
document.write("<a id="ok" href="http://www.mysite.com/master.m3u8?+siteContents+"><img src="./playicon.jpg"></a>");
});
</script>
Hi all i want to document.write a hyperlink image inside getjson
You can't (not reasonably*). document.write only works during the initial parsing of the page. If you use it after the page finishes loading, it completely replaces the page.
Instead, interact with the DOM. Several ways to do that, but the most obvious based on your code is to have the anchor initially-hidden and then show it after filling in the text area like this:
$("#ok").show();
Full Example: Live Copy | Live Source
(I've changed the playicon.jpg to your gravatar, since otherwise it shows as a broken image on JSBin)
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<form name="myform">
<textarea name="outputtext"></textarea>
</form>
<a id="ok" style="display: none" href="http://www.mysite.com/master.m3u8?+siteContents+"><img src="http://www.gravatar.com/avatar/f69cfb4677f123381231f97ea1138f8a?s=32&d=identicon&r=PG"></a>
<script>
(function($) {
$.getJSON('http://anyorigin.com/get?url=http://www.somesite.com/handelit.ashx&callback=?', function(data){
var siteContents = data.contents;
//writes to textarea
document.myform.outputtext.value = siteContents;
// shows the link
$("#ok").show();
});
})(jQuery);
</script>
</body>
</html>
* "not reasonably": IF your content were coming from the same origin as the document (it doesn't look like it is), you could do this with a synchronous ajax call. But that would be very bad design.
Please, use createElement instead of document.write
$.getJSON('http://anyorigin.com/get?url=http://www.somesite.com/handelit.ashx&callback=?', function(data){
var siteContents = data.contents;
//writes to textarea
document.myform.outputtext.value = siteContents ;
//Create A-Element
var link = document.createElement('a');
link.setAttribute('href', 'http://www.mysite.com/master.m3u8?' + encodeURIComponent(siteContents) );
link.id = 'ok';
//Append A-Element to your FORM-Element
var myForm = document.getElementsByTagName('form')[0];
myForm.appendChild(link);
//Create IMG-Element
var img = document.createElement('img');
img.setAttribute('src', './playicon.jpg');
//Append IMG-Element to A-Element (id='ok')
link.appendChild(img);
});