How to get elements from a cloned div - javascript

I have a div I have cloned that has elements inside it. I want to get the heading (h2) value out of the second child in the div
How do I go about this? I want to get the "bent over row" value from <div class="heading_add"><h2>Bent over row</h2>
// Make heading and button
let headingDiv = document.createElement('div');
headingDiv.classList = "heading_add"
let newh2 = document.createElement('h2');
newh2.innerHTML = itemRef.name;
headingDiv.appendChild(newh2)
videoCard.appendChild(headingDiv)
// Clones the div with video
newBtn.addEventListener('click', () =>{
const exercises = document.querySelector('.exercises');
let clone = videoCard.cloneNode(true); //Clones the div tags I'm trying to get
clone.defaultMuted = true;
let firstKid = clone.firstChild;
let secondChild = firstKid.firstChild.muted = true;
let meTest = firstKid.firstChild;
clone.classList.add('newVid');
console.log(meTest)
exercises.appendChild(clone)
});
<div class="videoCard newVid">
<div class="vid">
<video src="videostoredinfirebase" width="300" class="videoAdded" autoplay="" loop=""></video>
</div>
<div class="heading_add"><h2>Bent over row</h2>
<button class="add_video_btn">+</button></div>
</div>

Quick and dirty fix
function add() {
var myDiv = document.getElementById("test");
var divClone = myDiv.cloneNode(true);
document.body.appendChild(divClone);
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<script src="script.js" charset="utf-8"></script>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="test">
<h2>
This is a div
</h2>
</div>
<button onclick="add()">+</button>
</body>
</html>

Related

Keep body scrolled at the bottom unless user scrolls up in javascript

I have a program where the user types in something and then something outputs in the "console." The most recent entered thing stays at the bottom unless the user scrolls up
The body of my document seems to be where I can dd effects like hidden scroll to it. I read another post and used scrollTop and scrollHeight and it is not working.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href = "style.css">
</head>
<body id = "scroll">
<div id="game">
<div id="console">
</div>
</div>
<div id = "command-box">
<div id = "cmd">
<input id = "command" onkeypress = "doAThing(event);">
</div>
</div>
</div>
<script src = "variables.js"></script>
<script src = "code.js"></script>
</body>
</html>
var input = document.querySelector("#command");
var theConsole = document.querySelector("#console");
theConsole.scollTop = 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(input.value === "hi") theConsole.append("Hi!", p);
if(input.value === "ping") theConsole.append("Pong!", p);
}

Javascript adding an element into another element without id

Goal - I want to add "Start was Clicked!" inside the "main" element of my Html file.
This is the body of my Html File.
<body>
<h1></h1>
<p>First paragraph.</p>
<p class="intro">Second <span>paragraph</span>.</p>
<button id="start">Start</button>
<main></main>
</body>
This is my js code.
let button = document.querySelector('#start')
button.addEventListener('click', function(){
let elem = document.createElement('span');
elem.innerText = "Start was clicked!";
document.body.appendChild(elem);
}); // This just appends to bottom of the page, how would I add it to the main element without an id.
}
Use document.querySelector("main") to select the <main> element.
let button = document.querySelector('#start')
let main = document.querySelector('main')
button.addEventListener('click', function() {
let elem = document.createElement('span');
elem.innerText = "Start was clicked!";
main.appendChild(elem);
});
<h1></h1>
<p>First paragraph.</p>
<p class="intro">Second <span>paragraph</span>.</p>
<button id="start">Start</button>
<main></main>
Or you can use tagname instead.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1></h1>
<p>First paragraph.</p>
<p class="intro">Second <span>paragraph</span>.</p>
<button id="start">Start</button>
<main></main>
<script>
let btn = document.getElementById("start")
let main = document.getElementsByTagName("main")[0]
btn.addEventListener('click', function() {
let elem = document.createElement('span');
elem.innerText = "Start was clicked!";
main.appendChild(elem)
});
// This just appends to bottom of the page, how would I add it to the main element without an id.
</script>
</body>
</html>

adding check boxes to my unordered list with javascript

I am doing a project where i need to make a todo list and then when a user clicks the add button itll pull the info in and create a new li item and it to my ul list. But i need my li's to be created with a checkbox attribute attached to them as well and i am stuck, My code is below
// this creates a new li based on the entered value in the text box that it gets when you hit the button
function addItem() {
let newLi = document.createElement("li");
let myLiValue = document.getElementById('textBoxAdd').value;
let liTextNode = document.createTextNode(myLiValue);
newLi.appendChild(liTextNode);
// this just makes sure a user cant enter in a blank value
if (myLiValue == "") {
alert("Please Enter Something Before Hitting Add Item");
} else {
document.getElementById('theNewList').appendChild(newLi);
document.getElementById('textBoxAdd').value = "";
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>To-Do List</title>
<link rel="stylesheet" href="main.css">
<script src="main.js" async></script>
</head>
<body>
<main>
<h1>Brody's Wonderful List Of Things</h1>
<h3>Enter a Item and Press "Add Item" to Add to Your List</h3>
<section>
<div class="">
<label>Please Enter in Your TODO Item</label>
<input type="text" id="textBoxAdd">
<button type="button" id="addBtn" onclick="addItem()">Add Item</button>
</div>
</section>
<section>
<ul id="theNewList">
</ul>
</section>
</main>
</body>
</html>
To add a checkbox you can use the following:
let newCheckBoxID = 'checkbox_' + myLiValue;
let newCheckBox = document.createElement("INPUT");
newCheckBox.setAttribute("type", "checkbox");
newCheckBox.setAttribute("id", newCheckBoxID);
newLi.appendChild(newCheckBox);
You'll notice I added code to give the checkbox an ID. Chances are that you'll want to use the value of the checkbox in code somewhere so making sure it has ID set would be necessary. For actual use you'll want to massage the myLiValue to not have spaces and whatnot first before you make it part of an id. Also, I would probably add that id to some array somewhere too as the checkboxes are created...
Next, I would consider putting your text in a LABEL tag instead of leaving it as raw text in the LI
let newCheckLabel = document.createElement('LABEL');
newCheckLabel.setAttribute('for', newCheckBoxID);
let labelTextNode = document.createTextNode(myLiValue);
newCheckLabel.appendChild(labelTextNode);
newLi.appendChild(newCheckLabel);
// this creates a new li based on the entered value in the text box that it gets when you hit the button
function addItem() {
let newLi = document.createElement("li");
let myLiValue = document.getElementById('textBoxAdd').value;
let newCheckBoxID = 'checkbox_' + myLiValue;
let newCheckBox = document.createElement("INPUT");
newCheckBox.setAttribute("type", "checkbox");
newCheckBox.setAttribute("id", newCheckBoxID);
newLi.appendChild(newCheckBox);
let newCheckLabel = document.createElement('LABEL');
newCheckLabel.setAttribute('for', newCheckBoxID);
let labelTextNode = document.createTextNode(myLiValue);
newCheckLabel.appendChild(labelTextNode);
newLi.appendChild(newCheckLabel);
// this just makes sure a user cant enter in a blank value
if (myLiValue == "") {
alert("Please Enter Something Before Hitting Add Item");
} else {
document.getElementById('theNewList').appendChild(newLi);
document.getElementById('textBoxAdd').value = "";
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>To-Do List</title>
<link rel="stylesheet" href="main.css">
<script src="main.js" async></script>
</head>
<body>
<main>
<h1>Brody's Wonderful List Of Things</h1>
<h3>Enter a Item and Press "Add Item" to Add to Your List</h3>
<section>
<div class="">
<label>Please Enter in Your TODO Item</label>
<input type="text" id="textBoxAdd">
<button type="button" id="addBtn" onclick="addItem()">Add Item</button>
</div>
</section>
<section>
<ul id="theNewList">
</ul>
</section>
</main>
</body>
</html>

Create a new DOM with unique id based on the latest array

I want to create a new div element, with unique id from the latest array that i push every i click a create button , but it seem my code not working, here is my code below :
$(document).ready(function(){
var arr = [];
counter = 0;
$('#newDiv').on('click', function(){
$('.container').append('<div class="image">hallo</div');
counter ++;
arr.push(counter);
$('.image').attr('id',arr[arr.length-1]);
})
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div class="container"></div>
<button id="newDiv">create new div</button>
</body>
</html>
On each click you are setting id of each image element to last element in array, instead you can do something like this.
let arr = [], counter = 0;
$('#newDiv').on('click', function() {
arr.push(counter++)
const img = $('<div />', {
'class': 'image',
'id': arr.slice(-1)
}).text('hallo');
$('.container').append(img)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>
<button id="newDiv">create new div</button>
Or you can first push counter to array and then take last element for array with slice and use it as id.
let arr = [], counter = 0;
$('#newDiv').on('click', function() {
arr.push(counter++)
const img = $(`<div class="image" id=${arr.slice(-1)}>hallo</div>`)
$('.container').append(img)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>
<button id="newDiv">create new div</button>
First when you use classe query selector it would add the id to every element with that class so here is a work around you can use :
Add the add on the appending part
$(document).ready(function(){
var arr = [];
counter = 0;
$('#newDiv').on('click', function(){
counter ++;
arr.push(counter);
$('.container').append('<div id='+(arr.length-1)+' class="image">hallo '+(arr.length-1)+'</div');
})
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div class="container"></div>
<button id="newDiv">create new div</button>
</body>
</html>
Your original code is selecting all div with the image class and updating them all with the latest number.
I suggest creating the div adding the number to the new div only and then appending it to the container.
Please review the updated code below:
$(document).ready(function() {
var arr = [];
counter = 0;
$('#newDiv').on('click', function() {
counter++;
arr.push(counter);
// Create div
$('<div class="image"></div').text('hallo')
// Add ID attribute
.attr('id', arr[arr.length - 1])
// Apend new div to container
.appendTo('.container');
})
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div class="container"></div>
<button id="newDiv">create new div</button>
</body>
</html>

Button Loosing Reference after .appendChild

I want to make recursive Modals with vanilla JS, i.e there's a button in each modal that opens another Modal inside the current Modal.
So, I've a button that appends a div in a main parent div.
The problem is that the button loses it's onClick Property.
Can somebody please explain, why's this happening.
var modal = document.getElementById('myModal');
console.log("InitButton",modal);
var modalParent = document.querySelector('.modalParent');
console.log("ModalParent",modalParent);
var initBtn = document.getElementById("initialModal");
console.log("InitButton",initBtn);
var btn = document.getElementById("modalButton");
console.log("InitButton",btn);
modalParent.addEventListener('click',clickHandler)
initBtn.onclick = function() {
modal.style.display = "block";
}
var i = 0
function clickHandler(e){
if(e.target.matches('.modalButton')){
clone = modal.cloneNode(true);
clone.id = "new_Clone_" + i;
console.log("ClassName", clone.id);
modalParent.appendChild(clone);
i++;
}
}
This is the JS file
The HTML file is
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
</head>
<body>
<div class="Head">
<button id = "initialModal">Open Modal</button>
<div class="modalParent" id = "modalParent">
<div class="modal" id = "myModal">
<div class="modal-content">
<p>Some Text in Modal</p>
<button id = "modalButton">Open Modal</button>
</div>
</div>
</div>
</div>
<script src="main.js"></script>
</body>
</html>
Your issue was basically this line (matches is used wrongly)
if(e.target.matches('.modalButton')){ //you are matching a class while the modalButton has an id
Also as per same doc (link shared above) this is a non-standard API, so replace it with simple match
if (e.target.id.match('modalButton'))
var modal = document.getElementById('myModal');
console.log("InitButton", modal);
var modalParent = document.querySelector('.modalParent');
console.log("ModalParent", modalParent);
var initBtn = document.getElementById("initialModal");
console.log("InitButton", initBtn);
var btn = document.getElementById("modalButton");
console.log("InitButton", btn);
modalParent.addEventListener('click', clickHandler);
initBtn.onclick = function() {
modal.style.display = "block";
};
var i = 0;
function clickHandler(e)
{
if (e.target.id.match('modalButton'))
{
clone = modal.cloneNode(true);
clone.id = "new_Clone_" + i;
console.log("ClassName", clone.id);
modalParent.appendChild(clone);
i++;
}
}
<div class="Head">
<button id="initialModal">Open Modal</button>
<div class="modalParent" id="modalParent">
<div class="modal" id="myModal">
<div class="modal-content">
<p>Some Text in Modal</p>
<button id="modalButton">Open Modal</button>
</div>
</div>
</div>
</div>

Categories