I'm trying to change the content in a HTML using DOM JS. Rather than getting the elements by the P tag, I want to use the DIV ID.Is this possible?
In my HTML, I have two separate DIV classes, both named the same. I want one to display depending on what button the user clicks.
HTML:
<button type="button" onclick="changeContent(1)" >Example 1</button>
<button type="button" onclick="changeContent(2)" >Example 2</button>
<p id="demoX"></p>
<div class="ex1">
<h1> Example 1 </h1>
<p> nothing </p>
</div>
<div id="ex1">
<h1> Example 2 </h1>
<p> more of nothing </p>
</div>
JS:
function changeContent(inNum) {
var x = document.getElementById("ex1");
if (inNum == 1){
document.getElementById("demoX").innerHTML = x[0].innerHTML;
}
else if (inNum == 2){
document.getElementById("demoX").innerHTML = x[1].innerHTML;
}
}
How do I approach this?
First of all, you shouldn't give the same ID to more than one div so just give them both the class - 'ex1' - and then you select them by a javascript selector called getElementsByClassName('class-name') [replace class-name with the actual class name, in this case ex1] this function gets all the elements with this class name and stores them in an array. Then you do the logic for which button is pressed. And when a button is pressed you should set the display of the wanted div to 'block' [you should default it to hidden in CSS].
function showDiv(id) {
var divs = document.getElementsByClassName('ex1');
if (id === 'btn1') { divs[0].style.display = 'block' }
if (id === 'btn2') { divs[1].style.display = 'block' }
}
.ex1 {
width: 300px;
height: 300px;
background-color: green;
display: none;
margin: 50px;
}
<button id='btn1' onClick='showDiv(this.id)'>button 1</button>
<button id='btn2' onClick='showDiv(this.id)'>button 2</button>
<div class='ex1'>I'm div 1</div>
<div class='ex1'>I'm div 2</div>
you can also change the .style thing to change the inner html as you have done in your original code.
Related
I have three buttons in HTML, orders and products and supplier. I want when the user clicks orders order is being shown, when the user clicks products, the product is shown, and the name of the supplier when it is clicked.
function changedata(parameter){
if(parameter==0){
document.getElementById('myorders').style.fontSize="25px";
}
else if(parameter==1){
document.getElementById('myproducts').style.fontSize="25px";
}
else{
document.getElementById('mysupplier').style.fontSize="25px";
}
}
<button class="button" onclick="changedata(0)">ORDERS</button>
<button class="button" onclick="changedata(1)">PRODUCTS</button>
<button class="button" onclick="changedata(2)">SUPPLIER</button>
<div id="myorders">
<p>Laptop, Earphone</p>
</div>
<div id="myproducts">
<p>Earphone, smart watch</p>
</div>
<div id="mysupplier">
<p>Amazon, E-kart</p>
</div>
But it won't hide data and serve my need, I'm a beginner in web development, looking for kind help to show data only when the corresponding button is pressed.
Try giving each element a default value of display:none in your css, as such -
#myorders,
#mysuppliers,
#myproducts {
font-size: 25px;
display: none;
}
This will select each element and hide them right away.
Then, when a button is pressed, you can use
document.getElementById('___').style.display = 'block';
to then show that element.
Here is the final product:
function changedata(parameter){
if(parameter==0){
document.getElementById('myorders').style.display = 'block';
}
else if(parameter==1){
document.getElementById('myproducts').style.display = 'block';
}
else{
document.getElementById('mysupplier').style.display = 'block';
}
}
#myorders,
#myproducts,
#mysupplier{
font-size: 25px;
display: none;
}
<button class="button" onclick="changedata(0)">ORDERS</button>
<button class="button" onclick="changedata(1)">PRODUCTS</button>
<button class="button" onclick="changedata(2)">SUPPLIER</button>
<div id="myorders">
<p>Laptop, Earphone</p>
</div>
<div id="myproducts">
<p>Earphone, smart watch</p>
</div>
<div id="mysupplier">
<p>Amazon, E-kart</p>
</div>
If you would like to have the element toggle between hidden and shown on each button press, I recommend toggling a class with javascript, as such:
function changedata(parameter){
if(parameter==0){
document.getElementById('myorders').classList.toggle('active');
}
else if(parameter==1){
document.getElementById('myproducts').classList.toggle('active');
}
else{
document.getElementById('mysupplier').classList.toggle('active');
}
}
#myorders,
#myproducts,
#mysupplier{
font-size: 25px;
display: none;
}
#myorders.active,
#myproducts.active,
#mysupplier.active{
display: block;
}
<button class="button" onclick="changedata(0)">ORDERS</button>
<button class="button" onclick="changedata(1)">PRODUCTS</button>
<button class="button" onclick="changedata(2)">SUPPLIER</button>
<div id="myorders">
<p>Laptop, Earphone</p>
</div>
<div id="myproducts">
<p>Earphone, smart watch</p>
</div>
<div id="mysupplier">
<p>Amazon, E-kart</p>
</div>
There are slightly easier ways to connect each div to its corresponding button, and one of them is to use data attributes. We can add a data attribute to each button the text of which matches the id of its corresponding div.
(I'm assuming that when you click on one button all the other divs are hidden, and only its div shows.)
This example uses more modern JS techniques but I'll guide you through them, comment everything, and provide documentation at the end. You don't have to understand everything here but you're probably going to bump up against these things eventually, so you might as well take a look at them now.
Here's a rundown of how this all works:
Remove the inline listeners from the buttons. Modern JS uses addEventListener.
Wrap the buttons in a container. What we're going to use is a technique called event delegation. Instead of attaching listeners to every button we attach one to the container and this captures any events that "bubble up" the DOM from its child elements. We can then call a function when a child element is clicked.
The function does a few things. First it checks to see if the clicked element was actually a button. Then it hides all the "panels" by removing a class called "show" from them ("show" sets the element's display to block - initially all panels have their display set to none). Then based on the id from the button's data attribute it forms a selector with it, and we use that to target its corresponding div and apply the "show" class.
// Cache out buttons container, and all of the panels
const buttons = document.querySelector('.buttons');
const panels = document.querySelectorAll('.panel');
// Add an event listener to the buttons container
buttons.addEventListener('click', handleClick);
// When a child element of `buttons` is clicked
function handleClick(e) {
// Check to see if its a button
if (e.target.matches('button')) {
// For every element in the `panels` node list use `classList`
// to remove the show class
panels.forEach(panel => panel.classList.remove('show'));
// "Destructure" the `id` from the button's data set
const { id } = e.target.dataset;
// Create a selector that will match the corresponding
// panel with that id. We're using a template string to
// help form the selector. Basically it says find me an element
// with a "panel" class which also has an id that matches the id of
// the button's data attribute which we just retrieved.
const selector = `.panel[id="${id}"]`;
// Select the `div` and, using classList, again add the
// show class
document.querySelector(selector).classList.add('show');
}
}
.panel { display: none; }
.show { display: block; }
.button { text-transform: uppercase; }
.button:hover { cursor: pointer; background-color: #fffff0; }
<div class="buttons">
<button data-id="myorders" class="button">Orders</button>
<button data-id="myproducts" class="button">Products</button>
<button data-id="mysupplier" class="button">Supplier</button>
</div>
<div class="panel" id="myorders"><p>Laptop, Earphone</p></div>
<div class="panel" id="myproducts"><p>Earphone, smart watch</p></div>
<div class="panel" id="mysupplier"><p>Amazon, E-kart</p></div>
Additional documentation
addEventListener
classList
Destructuring assignment
forEach
matches
querySelector
querySelectorAll
Template string
I am developing a website which has a few filter buttons which are grouped into several groups. I am trying to find a way to set the class of one of these buttons to "filter-set" while all other buttons in the group are set to "not-set".
Each button is a DIV with a unique ID.
i have some bloated code where each button has its own function and sets the associated buttons to "not-set" but this seems inefficient and im sure there's a better way!
Bloated code example:
function setClassR(){
document.getElementById('filter_rare').className= 'filter-set';
document.getElementById('filter_common').className= 'not-set';
document.getElementById("filter_occasional").className = 'not-set';
}
function setClassC(){
document.getElementById('filter_rare').className= 'not-set';
document.getElementById('filter_common').className= 'filter-set';
document.getElementById("filter_occasional").className = 'not-set';
}
function setClassO(){
document.getElementById('filter_rare').className= 'not-set';
document.getElementById('filter_common').className= 'not-set';
document.getElementById("filter_occasional").className = 'filter-set';
}
I would like to be able to have a function for each group of filters which when run using an onClick=function() sets the clicked button to "filter-set" and all others to "not-set"
I have tried the following code but it doesnt appear to run:
function setClassSeas(rareClass, commonClass, occClass) {
setClass("filter_rare", rareClass);
setClass("filter_common", commonClass);
setClass("filter_occ", occClass);
}
function setClass(IDName, displayValue) {
var items = document.getElementById(IDName);
for (var i=0; i < items.length; i++) {
items[i].className = (displayValue? "filter-set" : "not-set");
}
}
UPDATE///
HTML Code for the Divs acting as buttons:
<div id="filter_rare" title="Rare"
class="not-set"
onclick="chosenFrequency('frequency=Rare'); setClassR();"></div>
<div id="filter_common" title="Common"
class="not-set"
onclick="chosenFrequency('frequency=Common'); setClassC();"></div>
<div id="filter_occasional" title="Occasional"
class="not-set"
onclick="chosenFrequency('frequency=Occasional'); setClassO();"></div>
If every button has a class, say filter-button, then you can address all buttons at once.
In modern development you should attach an event handler instead of using inline onclick handlers.
With all buttons having a common class you can find them all at once. I'm changing your buttons to look like this, adding the "filter-button" class and removing the onclick handler:
<div id="filter_rare" title="Rare"
class="filter-button not-set">Rare</div>
(I've put text in the div just to simplify this demonstration)
Now collect all the filter buttons:
let filters = document.querySelectorAll('div.filter-button');
This gets you a NodeList of elements (kind of like an Array but not one) You'll want to attach an onclick event handler to each of the buttons. To do this you can use the NodeList.forEach() call.
filters.forEach(node => node.addEventListener('click', someFunction));
In the function that gets called when you click a button, you want to clear any filter-set class that's currently set, put back the original not-set class, then set the filter-set class only on the button that was clicked. This will look something like this:
function someFunction(event) {
// again, use forEach to do the same thing to each filter button
filters.forEach( function(node) {
node.classList.remove('filter-set');
node.classList.add('not-set');
} );
// now add the 'filter-set' class on the button that was clicked
event.target.classList.add('filter-set');
}
The good thing about using classList instead of just doing className="something" is that classList can add/remove classes while leaving other classes alone; doing className="something" wipes out all the classes that are present and replaces them with "something".
Putting that all together, and using an anonymous function instead of named function gives this snippet:
let filters = document.querySelectorAll('div.filter-button');
filters.forEach(node => node.addEventListener('click',
function(event) {
console.log(event.target);
filters.forEach(function(node) {
node.classList.remove('filter-set');
node.classList.add('not-set');
});
event.target.classList.add('filter-set');
}));
/* Make these look like buttons; put a green border on them */
.filter-button {
min-height: 2ex;
max-width: 12em;
padding: .25em;
margin: .7em .3em;
background-color: lightgreen;
border: 2px solid green;
border-radius: 4px;
}
/* use a Red border on any button that has "filter-set" */
.filter-button.filter-set {
border: 2px solid red;
}
/* limit the height of the stack-snippet console */
div.as-console-wrapper {
max-height: 2.5em;
}
<div id="filter_rare" title="Rare"
class="filter-button not-set">Rare</div>
<div id="filter_common" title="Common"
class="filter-button not-set">Common</div>
<div id="filter_occasional" title="Occasional"
class="filter-button not-set">Occasional</div>
Using the class not-set is really redundant — you could just have no extra class on buttons by default and it would simplify things a little. Buttons would have the class(es) filter-button or filter-button filter-set.
Change your setClass function according to this. Hope it will work. document.getElementById() function will always return a single element (not a list of elements). Even if you have multiple elements having the same ID this function will always return the first element having the given ID. Do not forget to call your setClassSeas() function from html.
function setClassSeas(rareClass, commonClass, occClass) {
setClass("filter_rare", rareClass);
setClass("filter_common", commonClass);
setClass("filter_occ", occClass);
}
function setClass(IDName, displayValue) {
var item = document.getElementById(IDName);
item.className = displayValue ? "filter-set" : "not-set";
}
<div id="filter_rare" title="Rare" class="not-set"
onclick="chosenFrequency('frequency=Rare'); setClassSeas(true, false, false);"></div>
<div id="filter_common" title="Common" class="not-set"
onclick="chosenFrequency('frequency=Common'); setClassSeas(false, true, false);"></div>
<div id="filter_occasional" title="Occasional" class="not-set"
onclick="chosenFrequency('frequency=Occasional'); setClassSeas(false, false, true);"></div>
Here is another (as in "alternative") way to do it (but with jQuery, oh no!)
$('body').click(function(e) {
let $clicked = $(e.target);
console.log("Clicked " + $clicked.attr('id'))
if ($clicked.hasClass('filter')) {
let $filters = $clicked.closest('.filter-group').find('.filter');
let unset = $clicked.hasClass('set');
$filters.toggleClass('not-set', true);
$filters.toggleClass('set', false);
if (!unset) {
$clicked.toggleClass('not-set', false);
$clicked.toggleClass('set', true);
}
}
})
button.filter.not-set {
background: white;
}
button.filter.set {
color: white;
background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="filter-group">
<button id="filter_rare" class="filter not-set">
filter_rare
</button>
<button id="filter_common" class="filter not-set">
filter_common
</button>
<button id="filter_occasional" class="filter not-set">
filter_occasional
</button>
</div>
<div class="filter-group">
<button id="filter_one" class="filter not-set">
filter_one
</button>
<button id="filter_two" class="filter not-set">
filter_two
</button>
<button id="filter_three" class="filter not-set">
filter_three
</button>
</div>
I have a function that changes the src attribute of an icon when this one is clicked.
I also want it to hide the closest icon of the class fave_icon. I tried the following but it's not working:
function trash(event, trashcan){
event.stopPropagation();
if (trashcan.getAttribute('src') == "Iconos/tacho.png")
{
trashcan.src = "Iconos/warning.png"; //this works ok
var heart = trashcan.closest(".fave_icon");
heart.style.visibility = "hidden"
}
}
Basically I want to hide the closest element with class fave_icon to trashcan.
On the HTML I have this several times:
<button class="accordion">
<div>
<img src="Iconos/heart.png" onclick="fav(event,this);" alt="Fave" class="fave_icon">
</div>
<div>
<img src="Iconos/tacho.png" onclick="trash(event,this);" alt="Delete" class="delete_icon">
</div>
</button>
If fave_icon is a class then you have to place dot (.) before the class name as part of the selector.
Change var heart = trashcan.closest("fave_icon");
To
var heart = trashcan.closest(".fave_icon");
Based on the code and HTML you have provided you can do something like the following:
function trash(event, trashcan){
event.stopPropagation();
if (trashcan.getAttribute('src') == "Iconos/tacho.png"){
trashcan.src = "Iconos/warning.png"; //this works ok
var heart = trashcan.closest('button').querySelector('.fave_icon');
heart.style.visibility = "hidden";
}
}
<button class="accordion">
<div>
<img src="Iconos/heart.png" onclick="fav(event,this);" alt="Fave" class="fave_icon">
</div>
<div>
<img src="Iconos/tacho.png" onclick="trash(event,this);" alt="Delete" class="delete_icon">
</div>
</button>
From the trash icon, you go up a level to the div, select the previousElementSibling to get the heart's div, and then go down a level to the heart image itself.
Because the element is already included in the event target, you don't need to pass this. Or, even better, if you select the trash image first, you can avoid this entirely and use explicit variable names, which are easier to understand and debug.
But inline event handlers are essentially eval inside HTML markup - they're bad practice and result in poorly factored, hard-to-manage code. Seriously consider attaching your events with JavaScript, instead, eg: https://developer.mozilla.org/en/DOM/element.addEventListener
Another problem is that buttons should not have closing tags. Use a container element instead, like a div.
So, try something like this:
document.querySelectorAll('img[src="Iconos/tacho.png"]').forEach(img => {
img.onclick = () => {
const heartImg = img.parentElement.previousElementSibling.children[0];
heartImg.style.visibility = 'hidden';
};
});
<div class="accordion">
<div>
<img src="Iconos/heart.png" alt="Fave" class="fave_icon">
</div>
<div>
<img src="Iconos/tacho.png" alt="Delete" class="delete_icon">
</div>
</div>
you can add a class to the clicked element and use the general sibling combinator if the two items are adjacent.
document.getElementById("hide")
.addEventListener("click", (event) => {
event.target.classList.add('active');
}, false);
#hide.active~.element {
visibility: hidden;
}
#hide {
cursor: pointer;
}
.accordion {
padding: 15px;
background: lightgrey;
border-bottom: 1px solid grey;
}
.accordion div {
color: black;
margin-right: 20px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/icono/1.3.0/icono.min.css" rel="stylesheet" />
<div class="accordion">
<div class="icono-trash" id="hide"></div>
<div class="element icono-heart"></div>
</div>
I want to create a toggle button consisting eight buttons. If seven out of the toggle buttons are clicked it toggles two classes(and changes it's CSS styles).
If one(the daily button) out of the toggle buttons is clicked it toggles the styles of the other seven.
This is my code:
The toggleclass(this) function I predefined toggles the class1 to a class2 CSS style.
I tried doing this
<div id="menu1">
$(document).ready(function() {
$('#hey').click(function()
{
if($('#btnDiv,#btnDiv1,#btnDiv2,#btnDiv3,#btnDiv4,#btnDiv5,#btnDiv6').hasClass('class1')){
$('#btnDiv,#btnDiv1,#btnDiv2,#btnDiv3,#btnDiv4,#btnDiv5,#btnDiv6').toggleClass('class2')
}else{
$('#btnDiv,#btnDiv1,#btnDiv2,#btnDiv3,#btnDiv4,#btnDiv5,#btnDiv6').toggleClass('class2')
}
});
});
<div class="cols"><button id="btnDiv" onclick="toggleclass(this);monday();" class="class1"><h5>MONDAY</h5></button></div>
<div class="cols"><button id="btnDiv1" onclick="toggleclass(this);tuesday();" class="class1"><h5>TUESDAY</h5></button></div>
<div class="cols"><button id="btnDiv2" onclick="toggleclass(this);wednesday();" class="class1"><h5>WEDNESDAY</h5></button></div>
<div class="cols"><button id="btnDiv3" onclick="toggleclass(this);thursday();" class="class1"><h5>THURSDAY</h5></button></div>
<div class="cols"><button id="btnDiv4" onclick="toggleclass(this);friday();" class="class1"><h5>FRIDAY</h5></button></div>
<div class="cols"><button id="btnDiv5" onclick="toggleclass(this);saturday();" class="class1"><h5>SATURDAY</h5></button></div>
<div class="cols"><button id="btnDiv6" onclick="toggleclass(this);sunday();" class="class1"><h5>SUNDAY</h5></button></div>
<div class="cols"><button id="hey" onclick="toggleclass(this);daily();showdaily();" class="class1"><h5>DAILY</h5></button></div>
But it doesn't work. Help me out please
What do I do to get the daily button to change the styles of other buttons(if they are clicked) to class 1 when clicked and change back to class2 again
A straightforward answer using raw JavaScript would be truly appreciated as I'm pretty new to JavaScript.. :)
If you're doing this as a "learning exercise," then you're doing yourself no favors with all the extra HTML in there. I'd even go so far as to get rid of the divs containing each button, but that's just me.
So I'll post a starting point, but this is just an off-the-cuff thing, YMMV. Logically, walk through what you actually want to happen: when a button is clicked, you want to set ALL other buttons to "class1", and then you want to set the currently clicked button to "class2". Research using the javascript classList attribute, it's very handy for this.
I did edit this, as you're looking to TOGGLE the clicked button, so now the code sets all sibling buttons back to the class1, but then the last two lines actually toggle the class1/class2 rather than forcing the button on. For more on what you can do with classList, look at this.
Third time through. You not only want to be able to toggle the classes, but you want that select all button to toggle the selection of everything? Turn them all ON, turn them all OFF, or simply toggle each one? I've got it so that clicking 'Daily' will toggle all the selected buttons. Again, largely off-the-cuff, and largely playing here.
Based on your comment, clicking on 'Daily' toggles ALL day buttons to class1. I've commented out the section in the day handling to make the day selection be exclusive, but its still there if you need.
// First, store references to the bits we'll manipulate.
var menu = document.querySelector("#menu1");
var dayBtnEls = document.querySelectorAll(".day-button");
var allBtnEl = document.querySelector("#hey");
// Now, rather than adding them in the HTML, I'll
// attach my event listeners. The menu listens
// for clicks on the buttons, and the '#hey' button
// also has a listener. I could have done it all
// within that single menu listener, as that is
// also checking if the clicked button is #hey, but
// I figured "what the hey..."
menu.addEventListener("click", toggleDays);
allBtnEl.addEventListener("click", toggleAll);
/****
* Without knowing for sure, I've simply set the
* toggleAll function to go through all the day
* buttons and toggle their class1/class2. So having
* one of the buttons selected and clicking 'Daily'
* will leave all but that one selected.
* It's really up to you what you want for the toggle
* behavior, this is mostly just an example of what
* you COULD do.
****/
function toggleAll(event){
if (event.target.innerText == "Select All") {
// go through all the day button els.
for (var i=0; i<dayBtnEls.length; i++){
// toggle their class1/class2
dayBtnEls[i].classList.add("class1");
dayBtnEls[i].classList.remove("class2");
}
event.target.innerText = "Deselect All";
} else {
// go through all the day button els.
for (var i=0; i<dayBtnEls.length; i++){
// toggle their class1/class2
dayBtnEls[i].classList.remove("class1");
dayBtnEls[i].classList.add("class2");
}
event.target.innerText = "Select All";
}
}
/****
* again, without knowing what you're trying to do,
* I've set it so that clicking on a day button
* forces all the other day buttons to be toggled
* back to class1, then the clicked element will
* toggle back-and-forth from class1 to class2.
****/
function toggleDays(event){
// as we're listening at the menu level, and #hey
// is a child of menu, we need to filter that out.
if(event.target.id != "hey") {
var thisDayEl = event.target;
/****
* I'm commenting out this section, as it seems you
* don't want to have it be an exclusive toggle.
* I don't want to delete it yet, as I don't know
* for sure, but.
*
// set ALL buttons back to class 1...
for (var i=0; i<dayBtnEls.length; i++){
if(dayBtnEls[i] != thisDayEl) {
dayBtnEls[i].classList.remove("class2");
dayBtnEls[i].classList.add("class1");
}
}
****/
// Now, set just the clicked button to class2
thisDayEl.classList.toggle("class2")
thisDayEl.classList.toggle("class1");
}
}
.class1 {
color: #333;
background-color: #ccc;
}
.class2 {
color: #ccc;
background-color: #333;
}
.cols {
float: left;
}
.cols button {
height: 50px;
}
<div id="menu1">
<div class="cols">
<button id="btnDiv" class="day-button class1">MONDAY</button>
</div>
<div class="cols">
<button id="btnDiv1" class="day-button class1">TUESDAY</button>
</div>
<div class="cols">
<button id="btnDiv2" class="day-button class1">WEDNESDAY</button>
</div>
<div class="cols">
<button id="btnDiv3" class="day-button class1">THURSDAY</button>
</div>
<div class="cols">
<button id="btnDiv4" class="day-button class1">FRIDAY</button>
</div>
<div class="cols">
<button id="btnDiv5" class="day-button class1">SATURDAY</button>
</div>
<div class="cols">
<button id="btnDiv6" class="day-button class1">SUNDAY</button>
</div>
<div class="cols">
<button id="hey" class="all-button class1">Select All</button>
</div>
</div>
Doing the same thing WITH YOUR CODE, with a few very minor changes. Basically, rather than that really long selector list, I added another class to all the day buttons and I use THAT to gather them. I added a listener for the day buttons being clicked on that simply toggles their class1/class2, and the if statement you had in the daily button handler was doing the same thing in either case, so I just got rid of the if. Here is THAT example:
$(document).ready(function() {
$(".day-button").on("click", function() {
$(this).toggleClass("class1").toggleClass("class2");
})
$('#hey').click(function() {
$('.day-button').removeClass('class2').addClass("class1");
});
});
.class1 {
color: #333;
background-color: #ccc;
}
.class2 {
color: #ccc;
background-color: #333;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="menu1">
<div class="cols">
<button id="btnDiv" class="day-button class1">MONDAY</button>
</div>
<div class="cols">
<button id="btnDiv1" class="day-button class1">TUESDAY</button>
</div>
<div class="cols">
<button id="btnDiv2" class="day-button class1">WEDNESDAY</button>
</div>
<div class="cols">
<button id="btnDiv3" class="day-button class1">THURSDAY</button>
</div>
<div class="cols">
<button id="btnDiv4" class="day-button class1">FRIDAY</button>
</div>
<div class="cols">
<button id="btnDiv5" class="day-button class1">SATURDAY</button>
</div>
<div class="cols">
<button id="btnDiv6" class="day-button class1">SUNDAY</button>
</div>
<div class="cols">
<button id="hey" class="all-button class1">DAILY</button>
</div>
</div>
You could do something like this:
<style>
.class1 {
color: red;
}
.class2 {
color: green;
}
</style>
<div>
<button class="class1" onclick="changeClass(event)">Click me</button>
<button class="class1" onclick="changeClass(event)">Click me</button>
</div>
<script>
function changeClass(e) {
if (e.target.className.trim() === 'class1') {
e.target.className = 'class2';
} else {
e.target.className = 'class1';
}
}
</script>
Working example: https://jsfiddle.net/g12ua8d1/
I am using buttons for a tabbed navigation interface. I want to have the active tab red, and the rest black.
<div class="tabs">
<button type="button" onclick="selectTab(this);">Astringents</button>
<button type="button" onclick="selectTab(this);">Exfoliators</button>
<button type="button" onclick="selectTab(this);">Moisturizers</button>
</div>
function selectTab(activeTab){
var siblings = activeTab.parentNode.childNodes;
for (s in siblings){
s.style.color='black';
}
activeTab.style.color='red';
I am having problems accessing the siblings properly. There are more buttons than these three so I need to solve this dynamically. I will be using Ajax so this page will not reload.
You are trying to do extra work... Why not keep a reference to the currently selected tab, then when a new selection is made, reset its style.
Also, it is much better to use CSS classes than inline styles for this (this way, you don't need to muck about with Javascript to change how your tabs look):
<style>
.tab { color: black; }
.tab-selected { color: red; }
</style>
<div class="tab" onclick="selectTab(this)">Tab 1</div>
<div class="tab" onclick="selectTab(this)">Tab 2</div>
<!-- More tabs -->
<script>
var selectedTab = null;
function selectTab(tab) {
if (selectedTab) { selectedTab.className = 'tab'; }
tab.className = 'tab-selected';
selectedTab = tab;
}
</script>