This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 1 year ago.
I am trying to help a friend with making his website school project, but I ran into a problem. It was meant to have 3 text boxes with a button that can add more text boxes, I tried with document.write but it overwrites the whole page so I looked it up and I found out about document.createElement, which doesn't seem to work as well.
I don't know if anything in my code is incorrect.
<!DOCTYPE html>
<html>
<head>
<style>
.input {
margin-top: 50px;
}
.input .submit {
float: left;
}
.add {
margin-left: 100px;
margin-top: 50px;
width: 50px;
height: 50px;
font-size: 30px;
}
.gen {
float: right;
margin-right: 100px;
width: 400px;
height: 50px;
font-size: 25px;
}
.output {
position: fixed;
margin-top: 100px;
float: right;
margin-left: 400px;
}
</style>
<script language="javascript" type="text/javascript">
var input = document.createElement("<p>Hello</p>");
var container = document.getElementsByClassName("buttons");
container.appendChild(input);
</script>
</head>
<body>
<form class="buttons">
<input type="text" class="input">
<input type="submit" class="submit">
<br>
<input type="text" class="input">
<input type="submit" class="submit">
<input type="button" class="gen" value="Click to generate a random word">
<input type="text" class="output">
<br>
<input type="text" class="input">
<input type="submit" class="submit">
<br>
</form>
<input type="button" class="add" value="+" >
</body>
</html>
You're passing incorrect parameters to document.createElement - Documentation for this method can be found here: document.createElement
document.createElement accepts a tag name, but the other properties you have to add on through object manipulation.
var p = document.createElement("p");
p.textContent = "Hello";
document.body.appendChild(p);
Secondly you are using var container = document.getElementsByClassName("buttons") which is incorrect as well. You're trying to get the container element but asking for it to get a list of elements with the class name of "buttons". This returns an array and requires you to select the first option that's returned e.g. container[0].appendChild
In truth you should be using an ID instead of a class name. ID's are meant to be unique so that singular elements can be easily found within a document, class names are meant to be used to alter multiple elements. Given your situation though, you should alter your initial query so that it just returns the singular element using document.querySelector(".buttons")
var container = document.querySelector(".buttons");
All Together:
var p = document.createElement("p");
p.textContent = "Hello";
var container = document.querySelector(".buttons");
container.appendChild(p);
<form class="buttons">
</form>
A word of advice: judging from the code you've presented here you may not know the language well enough to assist in teaching it to others. That's not saying you don't have the aptitude or the ability, but it appears you need to spend more time studying the material before getting to that point.
You have a couple of issues, the first is that when your script runs, there are no elements for it to find, so you need to wait for the document to load using something like window.onload = function() { /* ... */ }. The second is the getElementsByClassName returns a HTMLCollection (essentially an array of nodes). You have to get the one that you want, or else the method appendChild won't exist (since the HTMLCollection has no such method). Also, createElement takes the name of the element, in this case p, and then you can use setInnerHTML to set the contents.
Your code should look something like:
window.onload = function() {
var input = document.createElement("p");
input.innerHTML = 'Hello';
var container = document.getElementsByClassName("buttons");
container[0].appendChild(input);
};
Related
I have the following structure .. I would like to remove div.son but keepdiv.grandson, is that possible ?! or changing your <tag> would also be a solution .. ex: changing from <fieldset> to a <div>, remembering that I do not have access to HTML, every change must be done using ** javascript **!
<div class="father">
<fieldset class="son">
<div class="grandson">Content here</div>
<div class="grandson">Content here</div>
<div class="grandson">Content here</div>
<div class="grandson">Content here</div>
</fieldset>
</div>
I tried to use the removeChild () function of ** javascript **, but it removes the entire element.
It's possible with vanilla JavaScript by deep cloning the node of grandson before removing anything else. and then appending it back to the parent. Of course if you want to place it somewhere else, you need to append needed logic of DOM traversing. (CSS section is only for visual validation of the result)
const grandson = document.querySelector('.grandson');
const father = grandson.closest('.father');
const clonedGrandson = grandson.cloneNode(true);
father.querySelector('.son').remove();
father.appendChild(clonedGrandson);
.father {
background-color: red;
padding: 20px;
}
.son {
background-color: blue;
padding: 20px;
}
.grandson {
background-color: green;
padding: 20px;
}
<div class="father">
<fieldset class="son">
<div class="grandson">
<p>Save me</p>
</div>
</fieldset>
</div>
You may take a look at this answer, try to use the search bar next time.
https://stackoverflow.com/a/170056/10944905
In case you just want to jump all over the answer.
var cnt = $(".remove-just-this").contents();
$(".remove-just-this").replaceWith(cnt);
I am trying to make a simple text editing box so that I can eventually post text to another section of a website. I'm attempting to make buttons to make text bold, italicized, add a code box etc, (hence insertAdjacentHTML not insertAdjacentText) but I decided to just start making sure I could get plain text to print to a textarea.
I have achieved this easily but now my question becomes how do I make it so that the button still affects the text area after a user has added text to it? the code below will happily type out "hello"'s up until you click on the textarea, and from that point on it refuses to and I can't figure out why.
window.hello = function(textarea) {
var obj = document.getElementById("text");
obj.insertAdjacentHTML('beforeend', 'hello');
}
<body>
<button onclick="hello()">hello</button>
<form>
<p></p>
<textarea id="text"></textarea>
</form>
</body>
As you can read from MDN a textarea can contain only Character data.
This is the reason because you cannot use insertAdjacentHTML and instead you can use the value.
If you need to add text in bold or ... you can use a contenteditable div element.
The snippet:
window.helloDiv = function() {
var obj = document.getElementById("textDiv");
obj.insertAdjacentHTML('beforeend', 'hello');
};
window.helloTxtArea = function() {
var obj = document.getElementById("textTxtArea");
obj.value += 'hello';
}
div {
width: 300px;
height: 100px;
border: 1px;
border-style: solid;
}
textarea {
width: 300px;
height: 100px;
margin-top: 10px;
}
<button onclick="helloDiv()">helloDiv</button>
<button onclick="helloTxtArea()">helloTextArea</button>
<form>
<p></p>
<div id="textDiv" contenteditable="true"></div>
<textarea id="textTxtArea" contenteditable="true"></textarea>
</form>
I am new all around HTML and JavaScript. Now I am trying to build a simple program that get input from the command line by the user and print it on the big console window. Now when I insert a simple text it does not print nothing into the box. Is there a special object should I use?
this is my code:
</head>
<body>
<img src="img/Mellanox_logo.jpg" alt="logo" align="middle">
<h1>Menu</h1>
<div id="container1" >
<div id="console" >
<p>
<script>
function showVal(){
var tmp = document.lineform.command_line.value;
document.getElementsByName('command_line').value = tmp;
}
</script>
</p>
</div>
<div >
<form id="form1" name="lineform" >
<input id="commandline" type="text" name="command_line" placeholder="Command line" onclick="showVal()" >
</form>
</div>
</div>
</body>
</html>
this is the css:
h1{
color: black;
text-align: left;
}
p{
color: black;
text-align: left;
font-size: 20px;
}
#container1{
width:1300px ;
}
#form1{
width:1300px ;
}
#console{
border:5px solid dodgerblue;
background-color: white;
height: 650px ;
padding-left: 5px;
margin-bottom: 5px;
position: relative;
width: inherit;
}
#commandline{
width: inherit;
border: 5px solid dodgerblue;
height: 30px;
padding-left: 5px;
font-size: 18px;
position: absolute;
}
this is how the command line and the window looks like:
1.- For this case i think you should be using getElementById instead of getElementsByName.
2.- I'd recommend not using a form, but instead have the input in the div's "root".
3.- A text input doesnt have a onclick (or at least it doesn't do what you want it to do)
4.- Add a button type input that executes the code through onclick="blabla();"
5.- i'd recommend putting your script at the end of the page since it works with the DOM and you're not using JQuery.
6.- add an id to the <p> element inside of the console <div>
<body>
<h1>Menu</h1>
<div id="container1">
<div id="console">
<p id="console_content">
</p>
</div>
<div>
<input id="commandline" type="text" name="command_line" placeholder="Command line">
<input id="commandButton" type="button" name="command_button" value="confirm" onclick="showVal();">
</div>
</div>
</body>
7.- new script:
<script>
function showVal() {
var tmp = document.getElementById("commandline").value;
document.getElementById('console_content').innerHTML += (tmp + "<br/>");
}
</script>
Here's a JFiddle so you can see it works:
https://jsfiddle.net/bLehLrum/
The function you are using returns an HTMLCollection, you need to the following:
Change,
document.getElementsByName('command_line').value = tmp;
To
document.getElementsByName('command_line')[0].value = tmp;
This gets the first element in the array, notice how there is an s at the end of getElements which suggests plural. This should help you in the future.
Reading Material
getElementsByName
Exdending Script47 answer, The problem is you are taking the value from input field and setting the same value again to it, That's why you are seeing any change/affect.
If by the box you mean the console, you should change your function with this
function showVal(){
// get the value of the input
var tmp = document.getElementById('commandline').value;
// add to the innerHTML of the console the tmp value
document.getElementById('console').innerHTML += "<p>"+tmp+"</p>";
}
document.getElementById
Your code try to reassign the value of command_line with the same value.
document.lineform.command_line.value could be the same as document.getElementsByName('command_line')[0]
I have a form and need to append a field as many times as required. If the button CLICK TO ADD ANOTHER FIELD is clicked the div should be appended. After the first append (onload), the div responses correctly but from the second one on, I am not getting the similar response from the div. Here is my JSFiddle
If I click on the TEST BUTTON , I get alert for the first div but on adding another div (by clicking the CLICK TO ADD ANOTHER FIELD button) , the button (TEST) doesn't work anymore for the second div onwards.
I tried clone() to help this but unable solve this one. May be I am not using it correctly.
To replicate the issue please follow the steps::
Click on the CLICK TO ADD ANOTHER FIELD button to add div
Click on the TEST button on the second div onwards
Please take a look and suggest. Thanks in advance.
You have to use delegation like $(document).on('click','.test',function(){
var count = 1;
$.fn.addclients = function(add){
var mydiv = '';
mydiv = '<div class="dataadd"><fieldset><legend>Test: '+add+'</legend><b>Test Name :</b> <input type="text" id="ct'+add+'" name="cname" value="" style="width:250px" />'+
' <button class="test" id="test" style="float:left;">TEST</button>'+
'<br>'+
'</fieldset></div>';
//$(".dataadd").clone().appendTo('#registerForm');
$('#registerForm').append(mydiv);
}
$.fn.addclients(count);
$(document).on('click','#btn',function(){
++count;
$.fn.addclients(count);
return false;
});
$(document).on('click','.test',function(){
alert("test");
return false;
});
.zend_form{
font-weight:bold;
font-size:10px;
width:358px;
float: left;
}
.dataadd{
font-weight:bold;
font-size:10px;
width:358px;
//border: 1px solid;
margin-top: 15px;
margin-bottom: 15px;
//padding: 5px;
//float:left;
}
.selectbox{
margin-top: 15px;
width:155px;
height:100px;
}
.buttonc{
background-color: #fff;
width:145px;
height:45px;
}
.selection_area{
font-weight:bold;
font-size:10px;
}
input {
width: 200px;
}
dt {
width:50%; /* adjust the width; make sure the total of both is 100% */
}
dd {
width:80%; /* adjust the width; make sure the total of both is 100% */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="registerForm" enctype="application/x-www-form-urlencoded" method="post" action=""><dl class="zend_form">
<dt id="firstname-label"><label for="firstname" class="required">First Name:</label></dt>
<dd id="firstname-element">
<input type="text" name="firstname" id="firstname" value="" style="width:200px; float:left;" /></dd>
<dt id="middlename-label"><label for="middlename" class="optional">Last Name</label></dt>
<dd id="middlename-element">
<input type="text" name="middlename" id="middlename" value="" style="width:200px" /></dd>
</form>
<div style='display:table;background-color:#ccc;width:99%;padding:5px;'>
<button class='buttonc' name='btn_sub' id='btn' style='float:left;'>CLICK TO ADD ANOTHER FIELD</button>
</div>
You write:
$('#btn').click(function(){ ... });
but this will only bind the event handler to elements currently on the page when running this code. So elements added later will not be covered by this code.
But first tip: do not use a HTML ID (#btn) if you want to repeat it. So instead use a class (.btn), to capture all elements.
And then the best way is to write something like:
$(document).on('click', '.btn', function() { ... } )
This will capture any click event on the document (you could use a container div instead --just easier to show now), and only run the callback if it matches the given selector (.btn).
all elements created after body load must use delegation to work
$("body").on("click",".test",function(){
alert("test");
return false;
});
This way, the event is attached to the body, witch always exists, but only triggers when the matched elements appear, no matter when they're created (before or after js is loaded)
Full disclosure, this is an assignment from an advanced JS class I'm taking. I've been trying to figure this out for a couple of weekends and it's driving me crazy! I'm far more familiar with jQuery than I am straight JS (which is one of the reasons I'm taking this class).
The webpage is supposed to take input from the user to create a <UL> list of links with some other strings associated that are related to the link. That part works just fine, what I can't figure out is why as soon as I'm done clicking on the Add Link button, the new link shows very briefly, then disappears! If I click the button very quickly, I can get several of them to show up, but as soon as I stop, all of them disappear.
I tried making a fiddle out of this, but clicking on the Add Link button gave me a POST error (which may be a clue to it's behavior?). If you cut & paste the code into an HTML file & run it, you'll see the behavior I'm describing.
I thought it had something to do with the init() function, so I tried running that at the bottom of the <body>, but that didn't make any difference. I also tried running it without an init, but couldn't figure out how to get the onclick listener initialized, even if it ran at the bottom of the <body>. I notice that even though I'm defining the favesList in global scope, it's still showing up as undefined after it should have been initialized with values (at least from my point of view). However, it looks like it's going out of scope instead which doesn't make sense to me. Console.log isn't providing me the reason why it's disappearing, or I haven't figured out a way to log the event.
I'm reasonably certain I'm missing a fundamental thing (like it's going out of scope for some reason?), so if someone could point out what that thing is I'd be grateful (I also don't need a definitive answer, just a nudge in the right direction, this is basically homework and I know I'm supposed to be figuring this out on my own, but I think a couple of Sundays of my time is giving it the college try).
Here's the code:
<!doctype html>
<html>
<head>
<title>Advanced JavaScript Project: Favorites and Tags</title>
<meta charset="utf-8">
<style>
body {
font-family: Helvetica, Ariel, sans-serif;
}
form {
display: table;
border-spacing: 5px;
width: 40%;
}
form p {
display: table-row;
}
form label {
display: table-cell;
text-align: right;
}
form input {
display: table-cell;
width: 95%;
}
span.comment {
font-size: 80%;
color: #777777;
}
span.tags {
font-size: 80%;
color: rgb(48, 99, 170);
}
#submit {
width: 20%;
}
</style>
<script>
window.onload = init;
var favesList;
console.log(favesList);
function init() {
//get submit button handle
var submit = document.getElementById("submit");
//add click handler to button to call method to add text to the list
submit.onclick = AddFavorite;
console.log("back in init");
}
function favorite(url, title, comment, tags){
console.log(this);
this.url = url;
this.title = title;
this.comment = comment;
this.tags = tags;
console.log(this);
}
function AddFavorite(){
var f = new favorite(
document.getElementById("url").value,
document.getElementById("title").value,
document.getElementById("comment").value,
document.getElementById("tags").value);
console.log(f);
favesList = document.getElementById("list");
console.log(favesList);
var node = document.createElement("LI");
var a = document.createElement('a');
a.appendChild(document.createTextNode(f.title));
a.href = f.url;
console.log(a);
node.appendChild(a);
node.appendChild(document.createTextNode(f.comment));
node.appendChild(document.createTextNode(f.tags));
console.log(node);
favesList.appendChild(node);
console.log(favesList);
}
</script>
</head>
<body>
<h1>Tag and save your favorites</h1>
<form id="form">
<fieldset>
<legend>Add a new favorite:</legend>
<label for="url">URL:</label>
<span><input id="url" type="url" placeholder="http://www.cnn.com" value="http://www.cnn.com"></span><br>
<label for="title">Title:</label>
<input id="title" type="text" value="CNN World News"><br>
<label for="comment">Comment:</label>
<input id="comment" type="textarea" value="Thoughts?"><br>
<label for="tags">Tags:</label>
<input id="tags" type="text" value="Enter keywords separated by commas"><br>
<input id="submit" type="submit" value="Add Link">
</fieldset>
</form>
<br>
<h1>List of favorites</h1>
<ul id="list"></ul>
</body>
</html>
You need to return false; as the last line in your AddFavorite() method, to stop the browser from processing the button and refreshing the page.