How to change elements selected using querySelectorAll - javascript

Suppose I have 3 buttons:
.all-buttons{
display:flex;
width: 100%
}
.bttn{
width: 33%
border: none;
background-color: blue;
padding: 20px 20px;
color: white;
}
<html>
<head><title>yes</title></head>
<body>
<div class="all-buttons">
<button class="bttn">BUTTON1</button>
<button class="bttn">BUTTON2</button>
<button class="bttn">BUTTON3</button>
</div>
</body>
</html>
As of my understanding I can use JavaScript const buttons = document.querySelectorAll('bttn'); which will create an array with every element with the class 'bttn'. How do I change the style of a button? For example, say I want to change the background-color of Button2 if I click on it. How do I get Button2 using classes in javascript?
I have tried this:
const buttons = document.querySelectorAll('link');
Array.from(buttons).forEach(el => {
el.addEventListener('click', function(event) {
//code
});
});
My end goal is to create a drop-down menu for each of the buttons but I would like to avoid adding an id for each button.
Any input is appreciated.

For getting elements by className, you have 2 options:
getElementsByClassName (without ".")
const buttons = document.getElementsByClassName('bttn');
querySelectorAll (with ".")
const buttons = document.querySelectorAll('.bttn');
And for changing the style of an element, you can use .style property on that element:
element.style.backgroundColor = 'blue';
So this code will help you:
const buttons = document.querySelectorAll('.bttn');
Array.from(buttons).forEach(el => {
el.addEventListener('click', function(event) {
el.style.backgroundColor = "blue";
});
});
Read more here.

First, document.querySelectorAll('bttn'); will not get elements with class equal to .bttn but it gets the elements with tag name equal to bttn.
You need to add the . like document.querySelectorAll('.bttn');
Then, you need to loop through with forEach and on each button add an event listener with addEventListener method on click, then you can change the color with style or create a class for the color and use classList methods.
const buttons = document.querySelectorAll('.bttn');
buttons.forEach(button => {
button.addEventListener('click', () => {
button.classList.toggle('red');
})
})
.all-buttons{
display:flex;
width: 100%
}
.bttn{
width: 33%
border: none;
background-color: blue;
padding: 20px 20px;
color: white;
}
.red {
background-color: red;
}
<html>
<head><title>yes</title></head>
<body>
<div class="all-buttons">
<button class="bttn">BUTTON1</button>
<button class="bttn">BUTTON2</button>
<button class="bttn">BUTTON3</button>
</div>
</body>
</html>

Hope it helps!
const buttons = document.querySelectorAll('.bttn'); // You must declare element's type; class (.) or id (#).
Array.from(buttons).forEach(el => {
el.addEventListener('click', function(event) {
el.style.color = "red"; // Added the line for changing the style of the button.
});
});
<button class="bttn">BUTTON1</button>
<button class="bttn">BUTTON2</button>
<button class="bttn">BUTTON3</button>

i think you need,
change element using queryseletorall
dropdown menu to each button
without using id to each button
to achieve this try like below,
const nodeList = document.querySelectorAll(".dropbtn");
const submenuList = document.querySelectorAll(".dropdown-content");
//alert(nodeList.length);
for (let i = 0; i < nodeList.length; i++) {
nodeList[i].addEventListener('click', function(event) {
submenuList[i].classList.toggle("show");
});
}
.dropbtn {
background-color: #3498DB;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropbtn:hover, .dropbtn:focus {
background-color: #2980B9;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {background-color: #ddd}
.show {display:block;}
<div class="dropdown">
<button class="dropbtn">Dropdown</button>
<div class="dropdown-content">
Link 1
Link 2
Link 3
</div>
</div>
<div class="dropdown">
<button class="dropbtn">Dropdown</button>
<div class="dropdown-content">
Link- 1
Link- 2
Link- 3
</div>
</div>
if any query please comment

Related

how can I get ID of element which I created by js [duplicate]

This question already has answers here:
Get ID of element clicked
(2 answers)
Closed 1 year ago.
wish all of you are fine , in my code below :
the user every time he clicked on element --> #crBtn, a new button should be create with different id (but all have the same className), for example if the user clicked on #crBtn three times that means 3 buttons will appear , now if I clicked on any of these button i want it to change its background-color and at the same time I need its id , how can i do that in js?
var idNum = 0;
function crBtn()
{
idNum++;
var button = document.createElement("button");
button.innerHTML="HERE";
button.setAttribute("class","name");
button.setAttribute("id","na"+idNum);
document.body.appendChild(button);
}
.name
{
background-color: aquamarine;
border: none;
width:300px;
height: 50px;
cursor: pointer;
margin-right: 10px;
margin-bottom:10px;
}
#crBtn
{
width:500px ;
height:60px;
background-color: blue;
border: none;
margin:30px;
color:white;
font-size: 30px;
}
.name:hover
{
background-color: skyblue;
color:aliceblue;
}
<body>
<button id = "crBtn" onclick="crBtn()">CLICK TO CREATE BUTTONS</button><br>
</body>
Pass event to the function. target property of the event object is your clicked element.
<button id = "crBtn" onclick="crBtn(event)">CLICK TO CREATE BUTTONS</button><br>
function crBtn(e){
console.log(e.target); //e.target is the button element
}
The following script defines a delegated click handler, bound to the body element of the document. Different actions are taken depending on which button was clicked.
var idNum = 0;
document.body.onclick=ev=>{
if (ev.target.id==="crBtn") crBtn()
else if (ev.target.className==="name") {
console.log("click on button with ID "+ev.target.id)
ev.target.style.backgroundColor="red";
}
}
function crBtn(){
idNum++;
var button = document.createElement("button");
button.innerHTML="HERE";
button.setAttribute("class","name");
button.setAttribute("id","na"+idNum);
document.body.appendChild(button);
}
.name
{
background-color: aquamarine;
border: none;
width:300px;
height: 50px;
cursor: pointer;
margin-right: 10px;
margin-bottom:10px;
}
#crBtn
{
width:500px ;
height:60px;
background-color: blue;
border: none;
margin:30px;
color:white;
font-size: 30px;
}
.name:hover
{
background-color: skyblue;
color:aliceblue;
}
<body>
<button id="crBtn">CLICK TO CREATE BUTTONS</button><br>
</body>

How to make single function for multiple dropdowns with same class to work?

When one dropdown button is clicked, show class is applied to all the dropdown contents despite applying it just to a child dropdown content.
Using different class name for different dropdown seems to work but that way the code becomes immense.
//Working JS (But using multiple classnames)
const homeBtn = document.querySelector(".home-btn");
const aboutBtn = document.querySelector(".about-btn");
const homeContent = document.querySelectorAll(".home-content");
const aboutContent = document.querySelectorAll(".about-content");
let showDropdown = false;
homeBtn.addEventListener("click", toggleHome);
aboutBtn.addEventListener("click", toggleAbout);
function toggleHome() {
if (!showDropdown) {
homeContent.forEach(item => item.classList.add("show"));
showDropdown = true;
} else {
homeContent.forEach(item => item.classList.remove("show"));
showDropdown = false;
}
}
function toggleAbout() {
if (!showDropdown) {
aboutContent.forEach(item => item.classList.add("show"));
showDropdown = true;
} else {
aboutContent.forEach(item => item.classList.remove("show"));
showDropdown = false;
}
}
.sideitem {
background: orange;
padding: 10px 0 0 10px;
border-bottom: 1px solid #fff;
}
.dropdown-btn {
padding: 5px;
cursor: pointer;
}
.dropdown-content {
display: none;
}
.dropdown-content.show {
display: block;
}
.dropdown-content a {
display: block;
color: #fff;
padding: 5px;
border-bottom: 1px solid #fff;
margin-left: 20px;
}
.dropdown-content a:hover {
background: #fa0;
color: #00f;
}
<ul class="sidelist">
<li class="sideitem">
<div class="dropdown-btn home-btn"> Home<i class="fas fa-caret-down"></i></div>
<div class="dropdown-content home-content">
Slider
Testimonal
</div>
</li>
<li class="sideitem">
<div class="dropdown-btn about-btn"> About<i class="fas fa-caret-
down"></i></div>
<div class="dropdown-content about-content">
About Us
Our Team
</div>
</li>
</ul>
Is there any simple way to solve this issue despite using the large code?
// Get all drop-down buttons
const dropDownButtons = document.querySelectorAll(".dropdown-btn");
// Get all drop down content elements.
const dropDownContent = document.querySelectorAll(".dropdown-content");
function handleClick(event) {
const main = event.target; // Use the event.target, the clicked element
const className = "show"; // Spcecify the class name one time
let myContent = null; // The drop down contents of the clicked item, if found
dropDownContent.forEach( elem => {
// Kludge: using parentNode since the clicked element is in it's own div.
// It would probably be better if the querySelector above selected
// the li-element, and then remove paretNode from the next statement.
if ( main.parentNode.contains(elem)) {
myContent = elem;
} else {
// Remove the class from every content except the clicked one.
elem.classList.remove(className);
}
});
// If the clicked have content, troggle if it is shown or not.
if (myContent) myContent.classList.toggle(className);
}
dropDownButtons.forEach( elem => elem.addEventListener("click", handleClick));
.sideitem {
background: orange;
padding: 10px 0 0 10px;
border-bottom: 1px solid #fff;
}
.dropdown-btn {
padding: 5px;
cursor: pointer;
}
.dropdown-content {
display: none;
}
.dropdown-content.show {
display: block;
}
.dropdown-content a {
display: block;
color: #fff;
padding: 5px;
border-bottom: 1px solid #fff;
margin-left: 20px;
}
.dropdown-content a:hover {
background: #fa0;
color: #00f;
}
<ul class="sidelist">
<li class="sideitem">
<div class="dropdown-btn home-btn"> Home<i class="fas fa-caret-down"></i></div>
<div class="dropdown-content home-content">
Slider
Testimonal
</div>
</li>
<li class="sideitem">
<div class="dropdown-btn about-btn"> About<i class="fas fa-caret-
down"></i></div>
<div class="dropdown-content about-content">
About Us
Our Team
</div>
</li>
</ul>

Change color second button with java script

I have two Red buttons. If you click a button the color should change to Green. If you click again it should return to Red.
Now I succeed to change the color of the first button, but not of the seccond button.
Has someone an idea?
I have already a java script that change the color of one button
var button = document.querySelector("button");
button.addEventListener("click", function() {
const curColour = button.style.backgroundColor;
if (curColour === 'red') {
button.style.backgroundColor = "green";
} else {
button.style.backgroundColor = "red";
}
});
button {
height: 40px;
width: 160px;
border: 4px;
border-radius: 20px 20px 20px 20px;
border-color: red;
color: yellow;
padding: 12px 15px;
text-align: center;
font-size: 16px;
cursor: pointer;
}
.button1 {
background: red
}
.button1:hover {
background-color: green;
}
<button id="bGeneral" class="button1" name="bGeneral"><b>General</b></button>
<!-- Create extra space -->
<p><br></p>
<!-- The Next Button Plates -->
<button id="buttonP" class="button1" name="buttonP"><b>Plates</b></button>
Expect to be able to change color of both buttons
You can use toggleClass. Also use querySelectorAll this will give all the buttons. Then iterate this collection and add event listener to it. .Inside callback function use classList.toggle to add or remove the class
var button = [...document.querySelectorAll("button")].forEach((item) => {
item.addEventListener("click", function() {
this.classList.toggle('toggleButtonColor')
});
})
button {
height: 40px;
width: 160px;
border: 4px;
border-radius: 20px 20px 20px 20px;
border-color: red;
color: yellow;
padding: 12px 15px;
text-align: center;
font-size: 16px;
cursor: pointer;
}
.button1 {
background: red
}
.button1:hover {
background-color: green;
}
.toggleButtonColor {
background: green;
}
<body style="background-color:#E3CEF6;">
<button id="bGeneral" class="button1" name="bGeneral"><b>General</b></button>
<!-- Create extra space -->
<p><br></p>
<!-- The Next Button Plates -->
<button id="buttonP" class="button1" name="buttonP"><b>Plates</b></button>
</body>
As Andreas already said in the comments. You need querySelectorAll instead of querySelector. That will give you a collection which you must loop through
var buttons = document.querySelectorAll("button");
for (const button of buttons) {
// ...
}
var buttons = document.querySelectorAll("button");
for (const button of buttons) {
button.addEventListener("click", function() {
const curColour = button.style.backgroundColor;
if (curColour === 'red') {
button.style.backgroundColor = "green";
} else {
button.style.backgroundColor = "red";
}
});
}
button {
height: 40px;
width: 160px;
border: 4px;
border-radius: 20px 20px 20px 20px;
border-color: red;
color: yellow;
padding: 12px 15px;
text-align: center;
font-size: 16px;
cursor: pointer;
}
.button1 {
background: red
}
.button1:hover {
background-color: green;
}
<button id="bGeneral" class="button1" name="bGeneral"><b>General</b></button>
<!-- Create extra space -->
<p><br></p>
<!-- The Next Button Plates -->
<button id="buttonP" class="button1" name="buttonP"><b>Plates</b></button>
You are using two different way to deal with the click. Use either onclick or addEventListener. Here is an example.
I haven't improved the inside of your function tho. Look at #brk answer for opti
function showOrHide(id, name) {
const button = document.getElementById(id);
const curColour = button.style.backgroundColor;
if (curColour === 'red' || !curColour) {
button.style.backgroundColor = 'green';
} else {
button.style.backgroundColor = 'red';
}
}
button {
height: 40px;
width: 160px;
border: 4px;
border-radius: 20px 20px 20px 20px;
border-color: red;
color: yellow;
padding: 12px 15px;
text-align: center;
font-size: 16px;
cursor: pointer;
}
.button1 {
background-color: red;
}
.button1:hover {
background-color: green;
}
body {
background-color: #E3CEF6
}
<button id="bGeneral" onclick="showOrHide(this.id, 'General')" class="button1" name="bGeneral">
<b>General</b></button>
<!-- Create extra space -->
<p><br></p>
<!-- The Next Button Plates -->
<button id="buttonP" onclick="showOrHide(this.id, 'Plates')" class="button1" name="buttonP"><b>Plates</b></button>
you can use id :
function showOrHide(id) {
var element = document.getElementById(id);
const curColour = element.style.backgroundColor;
if (curColour === 'red') {
element.style.backgroundColor = "green";
}
else {
element.style.backgroundColor = "red";
}
}
and in HTML:
<button id="bGeneral" onclick="showOrHide(this.id)" class="button1" name= "bGeneral" ><b>General</b></button>
<!-- Create extra space -->
<p><br></p>
<!-- The Next Button Plates -->
<button id = "buttonP" onclick="showOrHide(this.id)" class="button1" name= "buttonP" ><b>Plates</b></button>
This is the proper way with your thoughts
<!DOCTYPE html>
<html>
<head>
<style>
button {
height:40px;
width:160px;
border: 4px;
border-radius: 20px 20px 20px 20px;
border-color:red;
color: yellow;
padding: 12px 15px;
text-align: center;
font-size: 16px;
cursor: pointer;
}
.button1 { background: red }
.button1:hover {
background-color: green;
}
</style>
</head>
<body onload="beginfase()" style="background-color:#E3CEF6;" >
<button id="bGeneral" onclick="" class="button1" name= "bGeneral" ><b>General</b></button>
<!-- Create extra space -->
<p><br></p>
<!-- The Next Button Plates -->
<button id = "buttonP" onclick="" class="button1" name= "buttonP" ><b>Plates</b></button>
<script type="text/javascript">
//we are creating an array
var button = [];
button = document.querySelectorAll("button");
//we are binding the function to all the elements of the array
for(i=0;i<button.length;i++){
button[i].onclick = function(){
// this represent the elemement which is being clicked
if(this.style.backgroundColor === "red"){
this.style.backgroundColor = "green"
}
else{
this.style.backgroundColor = "red"
}
}
}
</script>
</body>
try use onclick method, and use querySelectorAll to select all the buttons
HTML
<button id="bGeneral" onclick="changeColor(this)" class="button1" name= "bGeneral" ><b>General</b></button>
<!-- Create extra space -->
<p><br></p>
<!-- The Next Button Plates -->
<button id = "buttonP" onclick="changeColor(this)" class="button1" name= "buttonP" ><b>Plates</b></button>
JS
function changeColor (value) {
var buttons = document.querySelectorAll(".button1");
let color = value.style.backgroundColor;
for (let i = 0; i < buttons.length; i++) {
if (color === 'red') {
buttons[i].style.backgroundColor = 'green'
} else {
buttons[i].style.backgroundColor = 'red'
}
}
}

Icon interfering with button click event

I have a button enclosing an icon. I believe the icon is interfering with my click event. I am only able to click on the icon margins to activate the onclick event, but nothing happens when I click on the icon. I replaced the icon with some text and the button onclick works perfectly fine. I have tried z-index to put the icon behind the button, but to no avail. Can someone explain why the icon blocks the click from occurring and how I can fix it?
html:
<div class="navMenu">
<button onclick="navClick()" class="navMenu-button"><i class="fas fa-bars"></i></button>
<div id="navList" class="navMenu-content">
Home
About
Resume
</div>
sass:
.navMenu{
position: relative;
display: inline-block;
margin-top:5px;
margin-left:5px;
&-button {
background-color: #615b5b;
border-radius:50%;
color: white;
padding: 7px;
opacity:0.7;
border:none;
font-size: 14px;
cursor: pointer;
}
&-button:hover, &-button:focus {
background-color: #615b5b;
}
&-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 200px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
&-content .navMenu-link{
color: $body-text-color;
padding: 12px 16px;
text-decoration: none;
display: block;
}
&-content .navMenu-link:hover {
background-color: #ddd;
}
&-show {
display:block;
}
}
js:
function navClick() {
document.getElementById("navList").classList.toggle("navMenu-show");
}
window.onclick = function(event) {
if (!event.target.matches('.navMenu-button')) {
var dropdowns = document.getElementsByClassName("navMenu-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var show = dropdowns[i];
if (show.classList.contains('navMenu-show')) {
show.classList.remove('navMenu-show');
}
}
}
}
This is happening becuase your are setting an event that verifies if the element clicked contains an especific class, and indeed when it clicks the icon, it won't match because the icon does not contains the class you can solve it asking if also the parent contains the class....
window.onclick = function(event) {
if (event.target.matches('.navMenu-button') ||
event.target.parentNode.matches('.navMenu-button')
) {
console.log("it matches...");
}
}
.icon {
background:red;
}
<button class="navMenu-button">this is the button
<div class="icon">this is the icon</div>
</button>
On the other hand you could reference the click event using the "onclick" method in this case it will solve it automatically..
var button = document.querySelectorAll('.navMenu-button')[0];
button.onclick = function() {
console.log("button clicked");
}

Why document.getElementById.style and $.css behave differently

I was wondering that the onclick method that is calling my function doesn't have access to the style value on the first click but it does on the second. I was wondering if for jQuery it would be the same but it seems like it's not.
I created a short code that shows the issue:
HTML:
<p class="flip" onclick="myFunction()">Click to show panel</p>
<div id="panel">
<p>panel</p>
</div>
CSS:
#panel, .flip {
font-size: 16px;
padding: 10px;
text-align: center;
background-color: #4CAF50;
color: white;
border: solid 1px #a6d8a8;
margin: auto;
}
.flip {
cursor: pointer;
}
#panel {
display: none;
}
Script:
function myFunction() {
console.log(document.getElementById("panel").style.display); //on first call returns empty string
console.log($("#panel").css("display")); // on first call returns none
const setPanel = (a) => {document.getElementById("panel").style.display = a;};
const getPanel = document.getElementById("panel").style.display;
(getPanel === "none") ? setPanel("block") : setPanel("none");
}
I am wondering why the behavior is the way it is and is it possible to retrieve the style directly without using jQuery?
jQuery internally uses .getComputedStyle() to determine the effective styles on an element rather than the ones explicitly defined on that element. .style only returns the explicit ones.
Observe:
function myFunction() {
console.log(window.getComputedStyle(document.getElementById("panel")).display); //on first call returns none
console.log($("#panel").css("display")); // on first call returns none
const setPanel = (a) => {document.getElementById("panel").style.display = a;};
const getPanel = window.getComputedStyle(document.getElementById("panel")).display;
(getPanel === "none") ? setPanel("block") : setPanel("none");
}
#panel, .flip {
font-size: 16px;
padding: 10px;
text-align: center;
background-color: #4CAF50;
color: white;
border: solid 1px #a6d8a8;
margin: auto;
}
.flip {
cursor: pointer;
}
#panel {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="flip" onclick="myFunction()">Click to show panel</p>
<div id="panel">
<p>panel</p>
</div>

Categories