How to change an HTML class with JavaScript using getElementsByClassName [duplicate] - javascript

This question already has answers here:
How to add/remove a class in JavaScript?
(13 answers)
Closed 5 years ago.
How to change a class with Javascript using getElementsByClassName. I got it to work a little but it won't change the class one at the time bet only do it one time to.
I click the button to change css class it do it on all the div and I can do it more in one time.
Here is my Code
function Button_Color(Show_This) {
var x = document.getElementById("Color_box");
var i;
var Show_This;
if (Show_This == 1)
{
var d = document.getElementsByClassName("id_blue");
d[0].className = "hid";
var o = document.getElementsByClassName("id_red");
o[0].className = " uhid";
}
if (Show_This == 2) {
var d = document.getElementsByClassName("id_blue");
d[0].className = "hid";
var o = document.getElementsByClassName("id_red");
o[0].className = " uhid";
}
}
Here is a like to show you how it looks now with html css js
https://jsfiddle.net/ee51o5h5/1/
I want it to show red only when you click the little red one and blue only when you click the little blue one.
i am dyslexic and from a non-english speaking country so sorry for any miss up.

i try this :
<body>
<section class="section-button-box">
<div class="box-button box-color01" onClick="Button_Color(1);">
</div>
<div class="box-button box-color02" onClick="Button_Color(2);">
</div>
</section>
<section class="section-color-box" id="Color_box">
<div class="main-color id_blue">
<div class="box-size box-color01">
</div>
</div>
<div class="main-color id_red">
<div class="box-size box-color02">
</div>
</div>
<div class="main-color id_blue">
<div class="box-size box-color01">
</div>
</div>
<div class="main-color id_red">
<div class="box-size box-color02">
</div>
</div>
</section>
</body>
JS:
/*| Blue box |*/
function Button_Color(Show_This) {
var x = document.getElementById("Color_box");
var i;
var Show_This;
var list = document.getElementsByClassName("main-color");
for(var i = 0 ; i < list.length; i ++ ){
if (Show_This == 1)
{
console.log(list[i].classList.contains("id_blue"));
if(list[i].classList.contains("id_blue")){
list[i].classList.add("uhid");
list[i].classList.remove("hid");
}
if(list[i].classList.contains("id_red")){
list[i].classList.add("hid");
list[i].classList.remove("uhid");
}
}
if (Show_This == 2) {
console.log(list[i].classList.contains("id_blue"));
if(list[i].classList.contains("id_blue")){
list[i].classList.add("hid");
list[i].classList.remove("uhid");
}
if(list[i].classList.contains("id_red")){
list[i].classList.add("uhid");
list[i].classList.remove("hid");
}
}
}
}
and css :
/*| Button Box |*/
.section-button-box{
height:100px;
width:100%;
background-color:aqua;
}
.box-button{
height:50px;
width:50px;
float:left;
}
/*| Color Box |*/
.section-color-box{
height:300px;
background-color:#c1c1c1;
width:100%;
}
.box-size{
height:100px;
width:100px;
float:left;
}
.box-color01{
background-color:blue;
}
.box-color02{
background-color:red;
}
.hid , .hid .box-size {
height:0px;
width:0px;
}
.uhid{
height:100px;
width:100px;
}
i add something to your code . Hope to sovle your issue.

you just need to find all elements in the desired class, iterate them and change their classes to the class that makes their color:
if (Show_This == 1)
{
document.getElementsByClassName("box-color02").forEach(function(element){
element.className = "box-size box-color01";});
}
if (Show_This == 2)
{
document.getElementsByClassName("box-color01").forEach(function(element){
element.className = "box-size box-color02";});
}

Related

Div Traversing with jquery [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I want to know that, when I click on next button than id="upper1" become id="upper2" and id="upper2" become id="upper3" and id="upper3" become id="upper1" and so on.
Jquery
$('#next').click(function() {
var $dives = $('div');
var total_div = $sel.length;
for (var i = 1; i <= total_div; i++) {
$dives.eq(i).attr('id', $dives.eq(i + 1).attr('id'));
}
});
CSS
#upper1{
background-color:red;
}
#upper2{
background-color:yellow;
}
#upper3{
background-color:orange;
}
HTML
<div id="upper1">9</div>
<div id="upper2">8</div>
<div id="upper3">7</div>
<button id="next">Next</button>
You may do something like this that may work with any number of element with any IDs:
$('#next').click(function() {
let $sel = $('.container > div')
let l = $sel.length;
let last = $sel.eq(l - 1).attr('id');
for (let i = l - 1; i >= 1; i--) {
$sel.eq(i).attr('id', $sel.eq(i - 1).attr('id'));
}
$sel.eq(0).attr('id', last);
})
#upper1 {
background-color: red;
}
#upper2 {
background-color: yellow;
}
#upper3 {
background-color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div id="upper1">9</div>
<div id="upper2">8</div>
<div id="upper3">7</div>
</div>
<button id="next">Next</button>
With jQuery, you may use:
$("#next").click(function() {
var i1 = $("#upper1");
var i2 = $("#upper2");
var i3 = $("#upper3");
i1.attr("id", "upper2");
i2.attr("id", "upper3");
i3.attr("id", "upper1");
});
You will need to put the code inside a block that waits for the page to load like:
$(document).ready(function() {
<code here>
});
The use of attr allows to set a new id to each of the former id´s. Check the jsFiddle.
Also, as noted by other people, this would be better done by having fixed id´s and changing classes that defined the attributes to rotate.
Is changing the ids themselves really the goal or rather swapping the elements? (with contents)
$('#next').click(function(){
$("#container").children().last().prependTo("#container");
})
#upper1{
background-color:red;
}
#upper2{
background-color:yellow;
}
#upper3{
background-color:orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div id="upper1">9</div>
<div id="upper2">8</div>
<div id="upper3">7</div>
</div>
<button id="next">Next</button>
Or if the goal is switching the colours and not the elements themselves, it can be done with classes instead of swapping the ids:
$('#next').click(function(){
$("[class^=upper]").each(function(){
this.className = "upper" + (((this.className.substring(5) + 1) % 3)+1);
});
})
.upper1{
background-color:red;
}
.upper2{
background-color:yellow;
}
.upper3{
background-color:orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="upper1">9</div>
<div class="upper2">8</div>
<div class="upper3">7</div>
<button id="next">Next</button>
I guess you actually want to shuffle the divs not replace ids.
let divs = $(yourDivSelector);
divs.first().prepend(divs.last());
This code would move the last to the top and thereby move the rest down one step.

One click multiple functions with arrays

I'm trying to create this piece of code in which an element is pushed into an array, displayed and get a style added which gives them a random hex color. I got the hex color and the pushing into the array partly done, but I can't seem to be able to add the style nor display the div… Here is my code so far:
JS
var colorBg = '#' + (Math.random() * 0xFFFFFF << 0).toString(16)
var elements = []
var el = '<div class="element bg"></div>'
document.getElementById("addEl").onclick = () => {
elements.push(el)
//console.log(elements)
for (i = 0; i < elements.length; i++) {
console.log(elements[i])
document.write(elements[i])
//elements[i].style.backgroundColor = colorBg
}
}
HTML
<div class="container">
<div class="element bg"></div>
</div>
<input type="button" value="Add Block" id="addEl"/>
CSS
html, body{
height:80%;
}
.container{
width:100%;
height:100%;
}
.element{
width:100px !important;
height:100px;
}
Do not use document.write(). Instead, create HTML elements with document.createElement() and then append them to other elements.
You can also just set their color and append them once when you create the element. No need to do all that for ALL the elements every time you click the button.
If you want to randomize the color of every element on every button press, you could instead select all of the elements, iterate over them, and randomize their color that way.
document.getElementById("addEl").onclick = () => {
var el = document.createElement("div");
el.className = ["element bg"];
var colorBg = '#' + (Math.random() * 0xFFFFFF << 0).toString(16)
el.style.backgroundColor = colorBg
document.getElementById("container").append(el)
}
html, body{
height:80%;
}
#container{
}
.element{
width:100px !important;
height:100px;
margin:10px;
border:1px solid black;
}
<div id="container">
</div>
<input type="button" value="Add Block" id="addEl"/>
To give structure to the code it is nice to have each operation as a separate function. Random color string generation, new DOM element construction (without displaying it), main actions. This way it is easy to read the code: can start reading at any point and understand what the lines of code are doing, not necessary having to learn the whole code logic.
What's happening here. It starts with a button click, which fires a "click" event, that has function addEl() bound to it. addEl() would acquire a new DOM element from createEl(), place it inside container element and push the element to the elements array if its required for some other functionality not covered in the original question.
function getColor() {
return '#' + (Math.random() * 0xFFFFFF << 0).toString(16);
}
function createEl(){
var el = document.createElement("div");
el.className = "element bg";
el.style.backgroundColor = getColor();
return el;
}
function addEl() {
var el = createEl();
container.appendChild(el);
elements.push(el);
}
var container = document.getElementById("container");
var elements = [];
document
.getElementById("addEl")
.addEventListener('click', addEl)
;
html, body{
height:80%;
}
#container{
width:100%;
height:100%;
}
.element{
width:100px !important;
height:100px;
float:left;
}
<div id="container"></div>
<input type="button" value="Add Block" id="addEl"/>
You would create elements using DOM methods instead of using document.write(). It's usage is discouraged. The following will do what you are after:
document.getElementById("addEl").addEventListener('click', () => {
let container = document.querySelector('.container');
let el = document.createElement("div");
el.className = 'element bg';
el.innerText = 'foo';
el.style.backgroundColor = getRandomColor();
container.appendChild(el);
});
function getRandomColor() {
return '#' + (Math.random() * 0xFFFFFF << 0).toString(16);
}
html, body{
height:80%;
}
.container{
width:100%;
height:100%;
}
.element{
width:100px !important;
height:100px;
}
<div class="container">
<div class="element bg"></div>
</div>
<input type="button" value="Add Block" id="addEl"/>
This can be simply done using jquery
$(function () {
var elements = []
var el = '<div class="element bg"></div>'
$("#addEl").click(function () {
var colorBg = '#' + (Math.random() * 0xFFFFFF << 0).toString(16)
var el = $("<div />",
{
class: "element bg",
css: {
width: "20px",
height: "10px",
backgroundColor: colorBg
}
});
elements.push(el)
$("#mycontainer").append(el);
});
})
html, body{
height:80%;
}
.container{
width:100%;
height:100%;
}
.element{
width:100px !important;
height:100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container" id="mycontainer">
<div class="element bg"></div>
</div>
<input type="button" value="Add Block" id="addEl"/>

Want to fetch the id of the different div elements on the click of p element using javascript

I have a page with p tags and div element, the div element is set with display:none in the starting so, I just want to display the different divs as shown below inside the body tag on the click of the p tag but i got stuck in fetching the different id of the divs. Please do help me out from this situation.Below is my code. Thanks
<script>
function toggle(id)// here is the function which gets the different ids of the div
{ var element = document.getElementById(id);
for(i=1; i<3; i++)
{
if(element[i].style.display == "none")
{
element[i].style.display = "block";
}
else
{
element[i].style.display = "none"
}
}
}
</script>
<body>
<p onclick="toggle('div1')">Sentence1</p>
<p onclick="toggle('div2')">Sentence2</p>
<div id="div1" name="Name 1" style="display:none; width:400px; height:300px; border:1px solid black; background-color:yellow;" id="div1">Barun Ghatak</div>
<div id="div2" style="display:none; width:400px; height:300px; border:1px solid black; background-color:black;" id="div2">Bhoopi</div>
</body>
You only have one of each div, so you don't need the loop. Just use
function toggle(id)// here is the function which gets the different ids of the div
{
var element = document.getElementById(id);
if(element.style.display == "none")
{
element.style.display = "block";
}
else
{
element.style.display = "none"
}
}
document.getElementById returns a single object and not an array.
If you want to get both the divs, I suggest using a class to get them.
If you wanted to only show one at a time, for example if you were building a tabs, then you could use this code to hide all the other divs first, then show only the one you want to toggle. Otherwise, if you're happy to toggle them, you can use the code posted by the others.
JS Fiddle demo: http://jsfiddle.net/ecs77e9a/
HTML
<p onclick="toggle('div1');">Sentence1</p>
<p onclick="toggle('div2');">Sentence2</p>
<div id="content">
<div id="div1" name="Name 1" style="display:none; width:400px; height:300px; border:1px solid black; background-color:yellow;" id="div1">Barun Ghatak</div>
<div id="div2" style="display:none; width:400px; height:300px; border:1px solid black; background-color:black;" id="div2">Bhoopi</div>
</div>
JS
function toggle(id)
{
//Hide all other divs first
var divs = document.getElementById('content').childNodes;
for ( var i = 0; i < divs.length; i++ ) {
if ( divs[i].nodeName == "DIV" ) {
var div = document.getElementById(divs[i].id);
div.style.display = "none";
}
}
//Show the one that's being requested
var element = document.getElementById(id);
element.style.display = "block";
}

How to make images change automatically

I am new to javascript and I am trying to do a featured content slider something like the top banner in this website http://www.homeplus.co.kr
As you can see, the top big banner changes automatically & also will change when user hovers over one of the list at the right.
Right now I am able to do the hovering part, but I am still stuck at the automatic changing content part.
Here's a sample jsfiddle: http://jsfiddle.net/StormSdq/5tWPy/2/
<div class="pi">a</div>
<div class="pi">b</div>
<div class="pi">c</div>
<div class="pi">d</div>
<div class="c1">I DREAM</div>
<div class="c1">OF LLAMAS</div>
<div class="c1">JUMPING AROUND</div>
<div class="c1">EATING BUSHES</div>
css:
.pi {
font-size:12px;
color:#000;
font-weight:700;
width:30px;
height:25px;
margin-right:10px;
background:transparent;
border-bottom:solid 1px black;
}
.c1 {
border:1px solid blue;
background:lightskyblue;
width:200px;
height:200px;
float:right;
margin-right:430px;
margin-top:-100px;
color:red;
font-size:25px;
text-align:center;
display:none;
}
javascript:
div = document.getElementsByClassName('c1');
div[0].style.display = 'block'
B = document.getElementsByClassName('pi');
B[0].onmouseover = function () {
blip(0);
};
B[1].onmouseover = function () {
blip(1);
};
B[2].onmouseover = function () {
blip(2);
};
B[3].onmouseover = function () {
blip(3);
};
function blip(y) {
div = document.getElementsByClassName('c1');
for (x = 0; x < (div.length); x++) {
div[x].style.display = 'none';
}
div[y].style.display = 'block';
}
Any help will be greatly appreciated
Try this:
var cur = 0; // current index
setInterval(autoAnim, 2000); // auto change every 2s
function autoAnim(){
if(cur > 3) cur = 0;
blip(cur);
cur++;
}
Here is jsfiddle
You can use the function setTimeout to call something after XX miliseconds.
var number=0;
setTimeout(automatic,5000); // every 5 seconds
function automatic(){
blip(number);
number++;
if (number > 4)
number=0;
alert("Hello");
setTimeout(automatic,5000);
}
You will probably want to make the function sleep when mouse is hover and some others condtions

Elements "jerk" back to right when I change their order

I am trying to create an infinite scroll of elements, and haven't found a plugin that was sufficiently lightweight/capable enough, so I'm trying to create my own.
So far it is working swimmingly, except for a slight jerkiness in the animation when I remove the first element and append it to the end of the parent. The example I've tossed up also has an issue where the elements lose their padding, for some reason, but that is not occurring in my actual code...
Fiddle:
http://jsfiddle.net/WtFWy/
Using the sample markup:
<section id="photos" class="bg-transparent-black">
<div class="red"></div>
<div class="blue"></div>
<div class="green"></div>
</section>​
#photos{
position:absolute;
bottom:1em;
width:100px;
height:225px;
padding:3px;
overflow:hidden;
white-space:nowrap;
}
#photos div{
height:100%;
width:50px;
padding:3px;
display:inline-block;
position:relative;
border:1px solid black;
}
.red{background:red;}
.blue{background:blue;}
.green{background:green;}
​
And JavaScript:
scrollImages = function(){
var photoArea = $('#photos');
var children = photoArea.children();
var firstChild = $(children[0])
var firstOffset=firstChild.offset();
if(document.elementLeft === false){
document.elementLeft = firstOffset.left;
}
if(document.elementWidth === false){
document.elementWidth=firstChild.outerWidth(true);
}
if(firstOffset.left < 0 && (Math.abs(firstOffset.left) > Math.abs(document.elementWidth))){
photoArea.append(firstChild);
firstChild.css('margin-left', 0 + 'px')
children = photoArea.children();
firstChild = $(children[0])
firstOffset=firstChild.offset();
document.elementLeft = firstOffset.left;
document.elementWidth=firstChild.outerWidth(true);
}else{
}
document.elementLeft -= 1;
firstChild.css('margin-left', document.elementLeft + 'px');
t = setTimeout(scrollImages, 100);
}
document.elementLeft = false;
document.elementWidth = false;
var t = setTimeout(scrollImages, 500);
$('#photos').mouseover(function(){clearTimeout(t)});
$('#photos').mouseout(function(){scrollImages()})
});
​
If you remove the padding: 3px from #photos the animation works properly.

Categories