Although my code works and I understand all of it, what I am stumped on is why parentElement works for the code below.
By my understanding, the parent element of the button element should be the div with class "child-div", so why then is the code still giving me the correct answer for each "shop-item-title" when clicking the "Okay" button?
Any clarity will be highly appreciated:
let addToCart = document.getElementsByClassName("button-ok");
function addToCartClicked(event) {
let button = event.target;
let shopItem = button.parentElement;
let title = shopItem.getElementsByClassName("shop-item-title")[0].innerText;
console.log(title);
}
for (let i = 0; i < addToCart.length; i++) {
let button = addToCart[i];
button.addEventListener("click", addToCartClicked);
}
<div class="body-container">
<div class="child-div">
<p class="shop-item-title">Chocolate</p>
<br />
<button class="button-ok">Okay</button>
</div>
<div class="child-div">
<p class="shop-item-title">Coke</p>
<br />
<button class="button-ok">Okay</button>
</div>
</div>
Related
I am trying to add an increasing count number when a button is clicked, within the container <div>.
My code is not working, what am I missing?
let taskCounter = 0;
let addTaskFunction = () => {
const container = document.querySelector(".container");
taskCounter++;
let counterInDiv = document.createElement(`<div> ${taskCounter} </div>`);
container.appendChild(counterInDiv);
};
document.getElementById('addTask').addEventListener("click", () => {
addTaskFunction();
});
<h1>Your tasklist for today</h1>
<div class="container">
<div class="inputPart">
<input id="taskInput" value="" placeholder="Fill in the following task here" />
<button id="addTask">Add task</button>
<button id="removeAllTasks">Delete tasks</button>
</div>
</div>
You need to use the tag name (div) for document.createElement then set the innerHTML instead of using the actual HTML code.
let taskCounter = 0;
let addTaskFunction = () => {
const container = document.querySelector(".container");
taskCounter++;
let counterInDiv = document.createElement("div"); // <--HERE
counterInDiv.innerHTML = taskCounter;
container.appendChild(counterInDiv);
};
document.getElementById('addTask').addEventListener("click", () => {
addTaskFunction();
});
<body>
<h1>Your tasklist for today</h1>
<div class="container">
<div class="inputPart">
<input id="taskInput" value="" placeholder="Fill in the following task here" />
<button id="addTask">Add task</button>
<button id="removeAllTasks">Delete tasks</button>
</div>
</div>
<script src="app.js"></script>
</body>
I believe that this is the code you want:
let taskCounter = 1;
const taskList = document.getElementById("taskList");
const addTaskBtn = document.getElementById("addTask");
addTaskBtn.addEventListener("click", () => {
let task = document.getElementById("taskInput").value;
let counterInDiv = document.createElement("div");
counterInDiv.textContent = `${taskCounter++}: ${task}`;
taskList.appendChild(counterInDiv);
});
const deleteTasksBtn = document.getElementById("removeAllTasks");
deleteTasksBtn.addEventListener("click", () => {
taskList.innerHTML = "";
taskCounter = 1;
});
<h1>Your tasklist for today</h1>
<div class="container">
<div class="inputPart">
<input id="taskInput" placeholder="Fill in the following task here" />
<button id="addTask">Add task</button>
<button id="removeAllTasks">Delete tasks</button>
</div>
<div id="taskList"></div>
</div>
I made a few changes:
You do not need a function for the event listener, you can put the code inside an anonymous function that is passed to the event listener
taskCounter should start at 1, not 0
If you want the delete tasks button to work, then you should put the tasks inside a different container that can be easily cleared. I used one with the ID of "taskList"
document.querySelector() only selects a single element, but you gave it a class of "container". If multiple <div>s have the class "container", then you will run into problems.
document.createElement takes a tag name as the parameter, not HTML code. You should use document.createElement("div") then set the .textContent to whatever you want.
I'm learning JavaScript and this is a practice scenario for me.
What I have already is a button that clones content, and within that content that has been cloned, there is a button to remove it.
When I click the button that prompts you to remove the content, it removes the first set of content.
What I want to happen is when you click the button that prompts you to remove the content, it removes the content related to that button and nothing else.
This is the CodePen link.
https://codepen.io/JosephChunta/pen/YzwwgvQ
Here is the code.
function addContent() {
var itm = document.getElementById("newContent");
var cln = itm.cloneNode(true);
document.getElementById("placeToStoreContent").appendChild(cln);
}
function removeContent() {
var x = document.getElementById("content").parentNode.remove();
}
// This is for debug purposes to see which content is which
document.getElementById('orderContent')
.addEventListener('click', function(e) {
const orderedNumber = document.querySelectorAll('.thisIsContent');
let i = 1;
for (p of orderedNumber) {
p.innerText = '' + (i++);
}
});
.contentThatShouldBeHidden {
display: none;
}
<div id="placeToStoreContent">
</div>
<button id="orderContent" onclick="addContent()">Add Content</button>
<div class="contentThatShouldBeHidden">
<div id="newContent">
<div id="content">
<p class="thisIsContent">This is a prompt</p>
<button onclick="removeContent()">Remove this</button>
<hr />
</div>
</div>
</div>
When you'r trying to remove by ID, it takes the first ID it finds.
To remove the correct content, send this onclick.
<button onclick="removeContent(this)">Remove this</button>
And handle it in your function:
function removeContent(el) {
el.parentNode.remove();
}
Example:
function addContent() {
var itm = document.getElementById("newContent");
var cln = itm.cloneNode(true);
document.getElementById("placeToStoreContent").appendChild(cln);
}
function removeContent(el) {
el.parentNode.remove();
}
// This is for debug purposes to see which content is which
document.getElementById('orderContent')
.addEventListener('click', function(e) {
const orderedNumber = document.querySelectorAll('.thisIsContent');
let i = 1;
for (p of orderedNumber) {
p.innerText = '' + (i++);
}
});
.contentThatShouldBeHidden { display: none; }
<div id="placeToStoreContent">
</div>
<button id="orderContent" onclick="addContent()">Add Content</button>
<div class="contentThatShouldBeHidden">
<div id="newContent">
<div id="content">
<p class="thisIsContent">This is a prompt</p>
<button onclick="removeContent(this)">Remove this</button>
<hr />
</div>
</div>
</div>
In your remove button, do this:
<!-- The "this" keyword is a reference to the button element itself -->
<button onclick="removeContent(this)">Remove this</button>
And in your javascript:
function removeContent(element) {
element.parentNode.remove();
}
My HTML
<div class="chapter">text text text </div>
<div class="chapter">text text text </div>
<button id="button">button</button>
My js
var button = document.querySelector('#button');
var chapter = document.querySelectorAll('.chapter');
for(var i = 0; i < chapter.length; i++){
button.addEventListener('click', function(){
for(var i = 0; i < chapter.length; i++) {
chapter[i].classList.add('active');
}
});
}
This adds the class of "active" on clicking the button.
But toggle doesn't work. Instead of
chapter[i].classList.add('active');
When I do,
chapter[i].classList.toggle('active');
the class of "active" does not toggle. console shows no error.
So I tried to check the class of "active" first & remove the class if the class exists. I know I was trying to reinvent the toggle function; as stated above, toggle wasn't working so I tried it anyway.
if (chapter[i].contains('active')){
chapter[i].classList.remove('active');
And I got a slew of error messages. This is as far as I got. I somehow felt that this wasn't going to work but just tried it anyway.
I am stumped.
Can anyone point out why classList.toggle isn't working in my code & how this can be fixed?
Thanks.
You have one too many loop. Remove the outer one:
var button = document.querySelector('#button');
var chapter = document.querySelectorAll('.chapter');
button.addEventListener('click', function(){
for(var i = 0; i < chapter.length; i++) {
chapter[i].classList.toggle('active');
}
});
.active{
color: red;
}
<div class="chapter">text text text </div>
<div class="chapter">text text text </div>
<div class="chapter">text text text </div>
<div class="chapter">text text text </div>
<button id="button">button</button>
var button = document.querySelector('#button');
var chapters = document.querySelectorAll('.chapter');
button.addEventListener('click', function(){
for(var index = 0; index < chapters.length; index++) {
if(chapters[index].classList.contains('active')){
chapters[index].classList.remove('active');
}else{
chapters[index].classList.add('active');
}
}
});
.active {
color: red;
}
<div class="chapter">text text text </div>
<div class="chapter">text text text </div>
<button id="button">Toggle Color</button>
This code is supposed to be looping and adding multiple divs, but it isn't working. When I click it, only one div appears. If I click again, nothing happens.
<body>
<div class="start" >
<div id = "coba">
</div>
<div id = "cobi">
</div>
</div>
<script>
var divs = document.getElementById("coba").addEventListener("click", function () {
for (var i = 1; i < 100; i++) {
var di = document.createElement('div');
document.getElementById('coba').appendChild(di);
}
});
</script>
</body>
Thanks for your help
Your code does not work because you did not do anything with the variable "i" in the for statement. If you look at the fiddles of user2181397 & meghan Armes you will see how they added a line in the script to put it to work.
I tested the below in my IDE and it works just fine:
<body>
<div class="start" style="margin-top:50px; color:black;">
<div id = "coba">
<p>Click Me</p>
</div>
<div id = "cobi">
</div>
</div>
<script>
var divs = document.getElementById("coba").addEventListener("click", function() {
for (var i = 1; i < 100; i++) {
var di = document.createElement('div');
di.innerHTML=i;
document.getElementById('coba').appendChild(di);
}
});
</script>
</body>
Is it possible to get the ids of the 2 div tags on clicking the button, using javascript?
<div id="main">
<div id="content">
</div>
<button onclick="function();">show it</button>
</div>
I have 2 div tags here. The 1st div is in the main div while the content div is inside the main div and the button is inside the main div as well.
Is it possible to get the main and content id of the 2 div tags on clicking the button?
EXPECTED OUTPUT when I press the button:
alert: main
alert: content
You need to pass the element to the function. Then you can use parentNode to get the DIV that contains the button. From there, you can use querySelector to find the first DIV in the parent.
function showIt(element) {
var parent = element.parentNode;
alert(parent.id);
var content = parent.querySelector("div");
alert(content.id);
}
<div id="main">
<div id="content">
</div>
<button onclick="showIt(this);">show it</button>
</div>
<div id="main2">
<div id="content2">
</div>
<button onclick="showIt(this);">show it</button>
</div>
<div id="main3">
<div id="content3">
</div>
<button onclick="showIt(this);">show it</button>
</div>
document.getElementById('button').onclick = function () {
var divs = document.querySelectorAll('div');
for (var i = 0; i < divs.length; i++) {
var id = divs[i].getAttribute('id');
alert(id);
}
};
http://jsfiddle.net/jm5okh69/1/
This should work in all browsers and uses the cleaner .id method.
var button = document.getElementById('button');
button.onclick = getIDs;
function getIDs(){
var id,divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
id = divs[i].id // .id is a method
alert(id);
}
}
<div id="main">
<div id="content"></div>
<button id="button">show it</button>
</div>