Javascript Question regarding appendChild - javascript

Im just learning javascript and I'm just wondering why this doesn't work. I've created a button and when it is clicked I assigned a function which is supposed to append some text to all my paragraphs. I don't know why it doesn't work:
<html>
<head>
<title>javascript test</title>
</head>
<body>
<script language="javascript" type="text/javascript">
function appendStuff(){
var node = document.getElementsByTagName("P");
node.appendChild.createTextNode('Here's some text');
return true;
}
</script>
<noscript>
Your browser doesn't support javascript.
</noscript>
<input type="submit" value="click me" onclick="appendStuff();" />
<p>
This is the first paragraph.
</p>
<p>
This is the second paragraph.
</p>
<p>
This is the third paragraph.
</p>
</body>
</html>

you should pass new node as argument to appendChild method, like here:
var nodes = document.getElementsByTagName("P");
for(var i=0; i<nodes.length; i++) {
nodes[i].appendChild(document.createTextNode("Here's some text"));
}

document.getElementsByTagName returns a list (array) of element instead of just one, you have to pick up the one you'd like to append (i.e. node[0])

Try this
<html>
<body>
<script language="JavaScript">
function function11() {
var myNode = document.createTextNode("New Text Node");
document.body.appendChild(myNode);
}
</script>
<button onclick="function11();">Create text node</button>
</body>
</html>

function appendStuff(){
var node = document.getElementsByTagName("P");
var txt = 'Here is some text';
var newT = document.createTextNode(txt);
node.appendChild(newT);
return true;
}
Try the above method!!!!

> <script language="javascript"
> type="text/javascript">
The language attribute has been deprecated for over a decade, it should not be used.
> function appendStuff(){ var node = document.getElementsByTagName("P");
> node.appendChild.createTextNode('Here's some text');
> return true;
> }
As others have pointed out, getElemetsByTagName returns a live NodeList, which has a length property and whose members can be accessed by index. Note that while it is array-like, it is not an array.
A text element can be appended to the first node in the NodeList using:
node[0].appendChild(document.createTextNode("Here's some text"));
However it is much safer to first see if node[0] exists before attempting to call one of its methods.
> <noscript> Your browser doesn't
> support javascript. </noscript>
The fact that a browser displays a noscript element doesn't necessarily mean that the browser doesn't support javascript. The description of a noscript element includes:
The NOSCRIPT element allows authors to provide
alternate content when a script is not executed.
W3C, HTML4.01, ยง18.3.1
> <input type="submit" value="click me"
> onclick="appendStuff();" />
An input with a type of submit is intended to be in a form and be used to submit the form. A more appropriate value for the type attribute here is "button". And the XML-style closing tag is unnecessary.

document.getElementsByTagName return 'array' of fetched doms rather than one dom. so you need to specify single dom with for loop of this array or sth likely.

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>

When I add <br> in a textfield it is taken as a command not a string

The below code take the string written in the textfield and put it inside the def div. When testing, if I entered (as a string inside the textfield) it is taken as command. It is not writing in the def div
<!DOCTYPE html>
<html>
<head>
<script>
function add() {
var inp = document.getElementById("text").value;
alert (inp);
document.getElementById("def").innerHTML += inp;
}
</script>
</head>
<body>
<textarea id="text"></textarea><br>
<button type="button" onclick="add()">submit</button>
<div id="def"></div>
</body>
</html>
Provided that the extra " is just a typo in the question you can write it as <br>.
< is <
> is >
If the extra " is a typo found in your code as well, you'd better remove it before trying anything else.
In Javascript, in order to prevent the parsing of HTML content in textarea and input elements, you can use innerText instead of innerHTML as shown below:
document.getElementById("def").innerText // instead of innerHTML
You should replace
document.getElementById("def").innerHTML += inp;
with
document.getElementById("def").textContent += inp;
to prevent processing the html tags

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.

Onchange Event in Javascript; How to input diffrent items

I am fairly new to javascript and I am 13. So I am new to events in javascript. I would like help on this code:
<head>
<script>
function myFunction()
{
var x=document.getElementById("fname");
if (x=="Kyle")
{
document.write("Correct!");
}
else
{
document.write("Incorrect!")
}
}
</script>
</head>
<body>
Enter your name: <input type="text" id="fname" onchange="myFunction()">
</body>
I want it to say correct when I type my name. Please help. Thanks
the line
if (x=="Kyle")
should read
if (x.value=="Kyle")
x represents the element, not the element's value.
I hope this helps. Feel free to ask if you have any other problems.
First create a div tag below your form and give it an id of something like "messageBox"
so:
<div id="messageBox"></div>
then replace
document.write("Correct!");
with
document.getElementById('messageBox').innerHTML = "Correct!";
and the same for incorrect.
All this does is create a div tag so that the javascript has somewhere to output the success/failure message.
You were oh so very close. You get the DOM element (getElementById), but you need to get the actual value of the element. Use x.value == "Kyle"

html visibility style doesn't work

I have an odd problem.
I have button, "NextButton" that i want to hide initially but then when a checkbox is clicked, it should appear.
Below code doesn't work and it doesn't give any error. I've tested it on IE9 and FireFox 13
I searched other questions but couldn't find the problem that i am having...
<html>
<head>
<script language="javascript">
function enableNext() {
alert("clicked");
var s1 = document.getElementsByName("NextButton");
s1.style.visibility = "visible";
}
</script>
</head>
<body>
<input type="submit" name="NextButton" value="Next" style="visibility:hidden;"/>
<input type="checkbox" onClick="enableNext()" />
</body>
</html>
An array is returned in your code and you are applying style to an array. Change it to the code below.
function enableNext() {
alert("clicked");
var s1 = document.getElementsByName("NextButton")[0];//Get the first and only button in your case
s1.style.visibility = "visible";
}
document.getElementsByName returns an array of matched elements, you have to loop over it and change the style of individual items in the array. You can use jQuery to handle it easily $("[name='NextButton']").css("visibility", "visible") or if you want to use css display property you can use $("[name='NextButton']").show() or .hide(). Additionally if you don't want to use jQuery you can just use an id and instead of using getElementsByName use getElementById, it will return a single element that you need.
You should use id in HTML element and then document.getElementById(). This will give exact matched element.
<script language="javascript">
function enableNext() {
alert("clicked");
var s1 = document.getElementById("NextButton");
s1.style.visibility = "visible";
}
</script>
<input type="submit" id="NextButton" name="NextButton" value="Next" style="visibility:hidden;"/>
I guess you should try using css instead javascript alone.
Try using
document.getElementsByName("NextButton")[0];

Categories

Resources