Javascript cloneNode for adding new elements - javascript

what I'm trying to do is. when I click
function runIt(text) {
var counter = 1;
var comment = document.getElementById("name");
comment.innerText = text;
comment.cloneNode(true);
comment.id += counter;
}
document.addEventListener("click", function(e){
runIt("test")
}, true);
I want it to ADD a new element underneath that output "test".
it's keep getting replaced. :(
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>t</title>
</head>
<body>
<p id="name" class="someclass"></p>
</body>
</html>

cloneNode returns the new code, which you can then append to the DOM. Also counter should be defined outside the function and then incremented each time.
var counter = 1;
function runIt(text) {
var comment = document.getElementById("name");
newcomment = comment.cloneNode(true);
newcomment.innerText = text;
newcomment.id += counter;
counter++;
document.querySelector('body').append(newcomment)
}
document.addEventListener("click", function(e){
runIt("test")
}, true);
<p id="name" class="someclass">-</p>

Related

Why isnt my button displaying value onto the div

I want the button with the id of number1 to display the value of 1 on to the input box which has the id of quest which is short for question.I also want to know if my code can be made more readable.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calucator</title>
<style>
body{
text-align: center;
}
</style>
<script>
const quest = document.getElementById("quest");
const data = quest.value;
const yourElement = document.createElement("div");
function nums(){
const num1 = document.getElementById('number1').innerText = 1;
data.textContent = num1;
}
function run() {
nums()
yourElement.textContent = data
quest.appendChild(yourElement);
}
</script>
</head>
<body>
<h1>Calucator</h1>
<input type="number" placeholder="Enter now" name="" id="quest">
<button onclick="run()">=</button>
<br>
<button onclick="" id="number1">1</button>
</body>
</html>
<script>
const quest = document.getElementById("quest");
const data = quest.value;
const yourElement = document.createElement("div");
//PROBLEM 1: You are not attaching yourElement to the DOM. See Element.insertBefore / Element.appendChild
function nums(){
const num1 = document.getElementById('number1').innerText = 1;
data.textContent = num1;
}
function run() {
nums()
yourElement.textContent = data
quest.appendChild(yourElement);
}
</script>
And
<button onclick="run()">=</button>
Problem 2: Don't use inline element event handling. It isn't safe and Content-Security-Policy won't allow it. Instead, use JavaScript Element.addEventListener(...)

How can I combine two event functions of properties such as JavaScript?

var input = document.querySelector('input');
var button = document.querySelector('button');
var question = document.querySelector('.p1')
var result = document.querySelector('.p2')
button.addEventListener("click",function(e){
e.preventDefault;
question.innerHTML = input.value;
input.value = "";
input.placeholder = question.textContent[question.textContent.length-1]+ " finished word?";
input.focus();
})
/*
button.addEventListener("click",function(ev){
ev.preventDefault;
if(question.textContent[question.textContent.length-1] === input.value[0])
{
question.innerHTML = input.value;
input.value = "";
result.innerHTML = "good"
input.focus();
}
else{
input.value = "";
result.innerHTML = "bad"
input.focus();
}
})
*/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p class="p1"></p>
<input type="text" placeholder="input first word">
<button type="button">submit</button>
<p class="p2"></p>
<script src="끝말잇기2.js"></script>
</body>
</html>
I am sorry that I asked you a question using a translator because I can't speak English.
I have a question in the JavaScript code.
First, the first function is input the first word, and the event is click.
The second function is the same as the first letter of the word you received, and the last letter is the same, so you put the first letter in the first letter.
These two functions can be combined, but I think both functions are duplicated because they are event clicks.
How can i write code that combines two functions and performs sequential functions?
One Function Solution
There is no need for two functions, you can write it as one function. Consider here that you don't reset the input.value twice when you combine both. Just reset it at the end of the function.
var input = document.querySelector('input');
var button = document.querySelector('button');
var question = document.querySelector('.p1')
var result = document.querySelector('.p2')
button.addEventListener("click", function() {
question.innerHTML = input.value;
input.placeholder = question.textContent[question.textContent.length - 1] + " finished word?";
input.focus();
if (question.textContent[question.textContent.length - 1] === input.value[0]) {
question.innerHTML = input.value;
input.value = "";
result.innerHTML = "good"
input.focus();
} else {
input.value = "";
result.innerHTML = "bad"
input.focus();
}
})
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p class="p1"></p>
<input type="text" placeholder="input first word">
<button type="button">submit</button>
<p class="p2"></p>
<script src="끝말잇기2.js"></script>
</body>
</html>
Call Consecutively Wrapper Function
If you want to use two functions you can do a wrapper function and inside it you can call your two other functions.
Then when the button get's pressed you call the wrapper function which will proceed the two other functions consecutively.
var input = document.querySelector('input');
var button = document.querySelector('button');
var question = document.querySelector('.p1')
var result = document.querySelector('.p2')
button.addEventListener("click", wrapperFunction);
function a() {
question.innerHTML = input.value;
input.placeholder = question.textContent[question.textContent.length - 1] + " finished word?";
input.focus();
}
function b() {
if (question.textContent[question.textContent.length - 1] === input.value[0]) {
question.innerHTML = input.value;
input.value = "";
result.innerHTML = "good"
input.focus();
} else {
input.value = "";
result.innerHTML = "bad"
input.focus();
}
}
function wrapperFunction() {
a();
b();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p class="p1"></p>
<input type="text" placeholder="input first word">
<button type="button">submit</button>
<p class="p2"></p>
<script src="끝말잇기2.js"></script>
</body>
</html>
I removed the preventDefault, then I added a setTimeout to changing input.value so both functions can run(with the input.value resource shared)
Because setTimeout is asynchronous, it would work well in situations like this, since it would wait until the other things finish running(I'm paraphrasing so don't quote me) then it will run.. making both functions work at the "same time"
var input = document.querySelector('input');
var button = document.querySelector('button');
var question = document.querySelector('.p1')
var result = document.querySelector('.p2')
button.addEventListener("click",function(e){
//e.preventDefault;
question.innerHTML = input.value;
setTimeout(()=>{input.value = "";},0)
input.placeholder = question.textContent[question.textContent.length-1]+ " finished word?";
input.focus();
})
button.addEventListener("click",function(ev){
//ev.preventDefault;
if(question.textContent[question.textContent.length-1] === input.value[0])
{
question.innerHTML = input.value;
setTimeout(()=>{input.value = "";},0)
result.innerHTML = "good"
input.focus();
}
else{
setTimeout(()=>{input.value = "";},0)
result.innerHTML = "bad"
input.focus();
}
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p class="p1"></p>
<input type="text" placeholder="input first word">
<button type="button">submit</button>
<p class="p2"></p>
<script src="끝말잇기2.js"></script>
</body>
</html>

Why is console.log(valu) returning an empty string?

I want to save the value of an input and use it to create a customized message with the name of the person. when I console it I get an empty string.
I was asked to add some more details to my post so I have added a prt sc image. Kindly see it.
let body = document.querySelector('body');
let startContainer = document.createElement('div');
let fom = document.createElement('form');
body.prepend(startContainer);
startContainer.prepend(fom);
let playerName = document.createElement('input');
fom.prepend(playerName);
let btn = document.createElement('button');
fom.appendChild(btn);
//startContainer.appendChild(btn);
btn.textContent='enta'
function wlcomeM (val){
return val + " you are welcome"
};
function player (playername, x, y){
return playername.setAttribute(x, y);
}
//player(playerName, 'type', 'text');
player(startContainer, 'id', 'cv');
player(playerName, 'placeholder', 'enta ur name');
player(playerName, 'type', 'text');
player(playerName, 'id', 'name1');
player(playerName, 'name', 'plname');
player(fom, 'name', 'form');
player(btn, 'onclick', 'wlcomeM()');
let valu = document.forms['form']['plname'].value;
let tx = wlcomeM(valu);
console.log(tx)
console.log(valu)
//write a function that welcome player;
function welcomeM (player){
return player + ' you are welcome';
};
let p = welcomeM('Barthlo');
console.log(p)
<!DOCTYPE HTML>
<html lang='en'>
<head>
<meta charset="UTF-8">
<meta name='viewport' content='width=device-width, initial-scale=1'>
<title>Start</title>
</head>
<body>
<script src='gameStart.js'></script>
</body>
</html>
Any help would be appreciated.
As your input box is blank as the default so the variable 'valu' is blank.
When you pass it to a function 'welcomeM' and set it to 'tx', 'valu' is not updated as you only return a new string from 'welcomeM'. Hence it is showing blank
Solution
You can archieve this by far more easily.
I would recommend using an eventlistener to listen when your button gets clicked.
btn.addEventListener('click', function(){//do something});
Then when it's pressed get the value of your input field
let val = input.value;
Call your function with the value of the input field and greet the user
function(user)welcomeM{
console.log("Welcome " + user);
}
// or better using template strings
function(user)welcomeM{
console.log(`Welcome ${user}`);
}
let body = document.querySelector('body');
let startContainer = document.createElement('div');
body.prepend(startContainer);
let playerName = document.createElement('input');
startContainer.prepend(playerName);
let btn = document.createElement('button');
startContainer.appendChild(btn);
//startContainer.appendChild(btn);
btn.textContent='enta'
//let valu = document.forms['form']['plname'].value;
//let tx = wlcomeM(valu);
//console.log(tx)
//console.log(valu)
//write a function that welcome player;
function welcomeM (player){
console.log( 'you are welcome ' + player)
};
// here my edits
btn.addEventListener('click', function(){
let val = playerName.value;
welcomeM(val);
})
<!DOCTYPE HTML>
<html lang='en'>
<head>
<meta charset="UTF-8">
<meta name='viewport' content='width=device-width, initial-scale=1'>
<title>Start</title>
</head>
<body>
<script src='gameStart.js'></script>
</body>
</html>

JavaScript querySelector not working when .value is added to it

I am creating my program which takes the user input on an Enter key.
I use the userInput with .value in the if statement and it works perfectly. But when I try to use it as a variable, nothing is outputted and nothing is in the console.
I tried to do querySelector("input['name = "command"]') to see if it might work but again, nothing outputted and it showed nothing in the console
var userInput = document.querySelector("input[name = 'command']")
var theInput = userInput.value.toLowerCase();
var theConsole = document.querySelector("#console");
theConsole.scrollTop = theConsole.scrollHeight;
var myScroll = document.getElementById("scroll");
function doAThing(event) {
var theKeyCode = event.keyCode;
if(theKeyCode === 13) {
acceptCommand();
setInterval(scrollUpdate, 1000)
}
}
function scrollUpdate() {
myScroll.scrollTop = myScroll.scrollHeight;
}
function acceptCommand() {
var p = document.createElement("p");
if(theInput=== "help") theConsole.append("Help is given!", p);
//using the keywords
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body id = "scroll">
<div id="game">
<div id="console">
</div>
</div>
<div id = "command-box">
<div id = "cmd">
<input type = "text" name = "command" id = "command" onkeypress = "doAThing(event);">
</div>
</div>
</div>
</body>
</html>
Replace the div#console element:
<div id="console">
to this input:
<input type="text" id="console">
You will want to refer to userInput.value instead of theInput. Because theInput is set to the value at the time of setting the variable and it doesn't get updated even though the value of userInput changing.

How to replace text in a html document using Javascript

I have written this code which I thought was correct, but although it runs without error, nothing is replaced.
Also I am not sure what event I should use to execute the code.
The test a simple template for a landing page. The tokens passed in on the url will be used to replace tags or tokens in the template.
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// gets passed variables frm the url
function getQueryVar(str) {
return 'Newtext'; // JUST SCAFFOLD FOR TESTING
}
function searchReplace() {
/**/
var t = 0;
var tags = Array('keyword', 'locale', 'advert_ID');
if (document.readyState === 'complete') {
var str = document.body.innerText;
for (t = 0; t < tags.length; t++) {
//replace in str every instance of the tag with the correct value
if (tags[t].length > 0) {
var sToken = '{ltoken=' + tags[t] + '}';
var sReplace = getQueryVar(tags[t]);
str.replace(sToken, sReplace);
} else {
var sToken = '{ltoken=' + tags[t] + '}'
var sReplace = '';
str.replace(sToken, sReplace);
//str.replace(/sToken/g,sReplace); //all instances
}
}
document.body.innerText = str;
}
}
</script>
</head>
<body>
<H1> THE HEADING ONE {ltoken=keyword}</H1>
<H2> THE HEADING TWO</H2>
<H3> THE HEADING THREE</H3>
<P>I AM A PARAGRAPH {ltoken=keyword}</P>
<div>TODO write content</div>
<input type="button" onclick="searchReplace('keyword')">
</body>
</html>
So when the documment has finished loading I want to execute this code and it will replace {ltoken=keyword} withe value for keyword returned by getQueryVar.
Currently it replaces nothing, but raises no errors
Your problem is the fact you don't reassign the replacement of the string back to it's parent.
str.replace(sToken,sReplace);
should be
str = str.replace(sToken,sReplace);
The .replace method returns the modified string, it does not perform action on the variable itself.
Use innerHTML instead innerText and instead your for-loop try
tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ t+'}','g'), getQueryVar(t)))
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// gets passed variables frm the url
function getQueryVar(str)
{
return'Newtext';// JUST SCAFFOLD FOR TESTING
}
function searchReplace() {
/**/
var t=0;
var tags =Array('keyword','locale','advert_ID');
if (document.readyState==='complete'){
var str = document.body.innerHTML;
tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ t+'}','g'), getQueryVar(t)));
//tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ tags[t]+'}', 'g'), getQueryVar(tags[t])));
document.body.innerHTML=str;
}
}
</script>
</head>
<body >
<H1> THE HEADING ONE {ltoken=keyword}</H1>
<H2> THE HEADING TWO</H2>
<H3> THE HEADING THREE</H3>
<P>I AM A PARAGRAPH {ltoken=keyword}</P>
<div>TODO write content</div>
<input type ="button" onclick="searchReplace('keyword')" value="Clicke ME">
</body>
</html>

Categories