Add css class using document.getElementsByClassName - javascript

I am trying to add css class using javascript but its not working
var x = document.getElementsByClassName('oldclassname');
var i;
for (i = 0; i < x.length; i++) {
x[i].className += 'newclassname';
}
but when I tried changing background it works
var x = document.getElementsByClassName("oldclassname");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.backgroundColor = "red";
}
Am I doing anything wrong while adding css file

className is a space separated list of class names. The problem with your code is that it doesn't separate the class names with spaces. Try this:
var x = document.getElementsByClassName('oldclassname');
var i;
for (i = 0; i < x.length; i++)
{
x[i].className += ' newclassname'; // WITH space added
}
Without the space, it has only one class name
<div class="oldclassnamenewclassname"></div>
//if use space
<div class="oldclassname newclassname"></div>//get two class name

Better use classList:
var x = document.getElementsByClassName('oldclassname');
for (var i = 0; i < x.length; i++) {
x[i].classList.add('newclassname');
}
.newclassname { color: blue; }
<div class="oldclassname">Hello, world!</div>

Hi there is a much simpler way to do this using javascript
TO add a class: -
document.getElementsByClassName('otherClassName')[0].classList.add('newClassName');
To remove a class:-
document.getElementsByClassName('otherClassName')[0].classList.remove('newClassName');
Hope this helps :)

It works . Check your target class name formation.
Sample Code.
<html>
<head>
<style>
.classFrom{
font-family: sans-serif;
color: red;
}
.classTo{
font-family:cursive;
color: blue;
}
</style>
<script type="text/javascript">
function clickme(){
var elmList = document.getElementsByClassName('classFrom');
for (i = 0; i < elmList.length; i++)
{
elmList[i].className += " classTo";
}
}
</script>
</head>
<body>
<div class="classFrom">SampleText</div>
<button onClick="clickme()">ChangeCSS</button>
</body>
</html>

Related

Error in javascript code for facebook

I wrote some code to like all posts on Facebook.
var inputs = document.getElementsByClassName('_15ko _5a-2 touchable');
for(var i=0; i<inputs.length;i++) {
inputs[i].click();
};
The code is working well but the class '_15ko _5a-2 touchable' is the same class for (unlike)
So, When I scroll the page , More posts appear and trying to put the code again , The code working well with new posts but it remove likes from old posts.
Is there any solution?
You can try to check the innerHTML of the target, if the value is "Like" the click event is activated, if the value is "Dislike" the script ignore, example:
var inputs = document.getElementsByClassName('_15ko _5a-2 touchable');
for(var i=0; i<inputs.length;i++) {
if (inputs[i].innerHTML == "Like") {
inputs[i].click();
}
};
This will work if the button is something like:
<a class="_15ko _5a-2 touchable">Like</a>
To ignore the _2q8z class you can use the length of the className property, example:
//_15ko _5a-2 touchable = 21 (length)
var inputs = document.getElementsByClassName('_15ko _5a-2 touchable');
for(var i=0; i< inputs.length;i++) {
if (inputs[i].className.length == 21) {
inputs[i].click();
}
};
I will put a working example, hope it helps.
function Test() {
var elems2 = 0;
elems = document.getElementsByClassName("test1");
for (var x = 0; x < elems.length; x ++) {
elems2 ++;
}
alert(elems2 + " elements");
}
function Filter() {
var elems2 = 0;
elems = document.getElementsByClassName("test1");
for (var x = 0; x < elems.length; x ++) {
if (elems[x].className.length == 5) {
elems2 ++;
}
}
alert(elems2 + " elements");
}
.test1 {
display: block;
padding: 10px;
background: #f1f1f1;
margin: 10px;
}
<div class="test1">Element</div>
<div class="test1">Element</div>
<div class="test1">Element</div>
<div class="test1 _2qz8">Element to ignore</div>
<div class="test1 _2qz8">Element to ignore</div>
<input type="button" value="Count All Elements" onClick="Test();">
<input type="button" value="Count only with class test1" onClick="Filter();">

(vanilla javascript calculator) How do I get the nodeValue from this nodeList?

What I'm trying to do is grab the node that was clicked and add it to the innerHTML of the screen I have set up. However, it seems as though my for loop is completing before I can get that value. In my case, keys[3] doesn't exist, so it is returning an error, but I would like to have the loop stop on the 'clicked' element and grab that value.
JS Bin snippit
What you need to do is use textContent instead of nodeValue to get 1, 2, or 3. Next, use this instead of keys[i].
var screen = document.getElementById("screen");
var keys = document.querySelectorAll('.keys');
for (var i = 0; i < keys.length; i++) {
keys[i].addEventListener('click', function() {
screen.innerHTML += this.textContent;
});
}
#calculator {
width: 500px;
height: 600px;
border: 1px solid black;
}
#screen {
width: 100%;
height: 100px;
border: 1px solid black;
}
.keys {
width: 24%;
display: inline-block;
border: 1px solid black;
height: 50px;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="calculator">
<div id="screen">
</div>
<div class="keys">1</div>
<div class="keys">2</div>
<div class="keys">3</div>
</div>
</body>
</html>
Now this should be working properly as it gets the text content, and instead of keys[i], it uses this as i doesn't exist outside the loop. this references the current element. You could always define the anonymous function outside, and use a for-each loop.
The i variable exists only in the loop, it does not exist in the click event.
Try changing this:
screen.innerHTML += keys[i].firstChild.nodeValue;
To this:
screen.innerHTML += this.outerHTML;
for (var i = 0; i < keys.length; i++) {
keys[i].addEventListener('click', function(e) {
console.log(e, e.target)
screen.innerHTML += e.target.innerHTML;
});
i would use e.target to get anything out of div.
this feels more clean.
That is if you goal is to get any text that is in a container.
Although this would not be the most effective way to make a calculator.
http://jsbin.com/rifekejivi/1/edit?html,css,js,console,output
I would use let not var. This works:
for (let i = 0; i < keys.length; i++) {
keys[i].addEventListener('click', function() {
screen.innerHTML += keys[i].firstChild.nodeValue;
});
Ok: Edit:
var screen = document.getElementById("screen");
var keys = document.querySelectorAll('.keys');
var val = 0;
screen.innerHTML = 0;
for (let i = 0; i < keys.length; i++) {
keys[i].addEventListener('click', function() {
val += parseInt(keys[i].firstChild.nodeValue);
screen.innerHTML = val;
});
}
And to clarify: I would (allways) use let i = 0 in a loop because it also works with async operations in a loop because it is a block scope.
Not applying to this particular case but try this:
var x = [1,2,3,4];
for(var i = 0; i<x.length; i++){
window.setTimeout(function(){
console.log(i);
},Math.random())
}
//console.log returns: 4 4 4 4
for(let i = 0; i<x.length; i++){
window.setTimeout(function(){
console.log(i);
},Math.random())
}
//console.log returns 0 1 2 3
See the difference?
just add a click event to the body, and check if the targets class name equals key, then add the textContent of the target to screen
"use strict"
var screen = document.getElementById("screen");
var keys = document.querySelectorAll('.keys');
// for (var i = 0; i < keys.length; i++) {
// keys[i].addEventListener('click', function() {
// screen.innerHTML += this.textContent;
// });
// }
document.body.addEventListener('click', function(e) {
let target = e.target;
switch(target.className) {
case "keys":
screen.innerHTML += target.textContent;
break;
default:
}
})

How to append divs into another div inside a variable?

So, I am trying to create a HTML code generator just for fun. My actual problem is: How can I append divs from a loop inside another div that does not exist and is saved in a variable?
I hope I have been clear, thank you.
My little JavaScript until now:
colCont = $("<div class=\"stab-cont\"><div class=\"stab-row\"></div></div>");
function repeat(n) {
for (var i = 1; i < n + 1; i++) {
//Here I need to insert the n DIVs generated by this loop
}
}
repeat(3);
console.log(colCont);
JSFiddle: http://jsfiddle.net/qo3vdwhv/
Maybe I am under thinking it here, but this should work.
My code:
colCont = $("<div class=\"stab-cont\"></div>");
function repeat(n) {
for (var i = 1; i < n + 1; i++) {
$("<div class=\"stab-row\"></div>").appendTo(colCont); //build your div like you did with "colCont" and append the new div to colCont
}
}
repeat(3);
colCont.appendTo($("body"))
.stab-cont div {
border: 1px solid #c00;
margin: 10px;
float: left;
width: 200px;
height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here's something to consider; instead of making your repeat() function dependent on colCont, make it a jQuery function instead.
In this case I've created a function that will repeat the contents of a jQuery object N times (N >= 1).
colCont = $("<div class=\"stab-cont\"></div>");
jQuery.fn.times = function(n) {
var len = this.length;
for (var i = 1; i < n; ++i) {
for (var k = 0; k < len; ++k) {
this.push(this[0].cloneNode(true));
}
}
return this;
};
colCont
.append($('<div class="stab-row"></div>').times(3))
.appendTo('body');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Adding elements on loop jQuery

I am trying to generate a row of 16 boxes on load of webpage.
Here is my code:
var box = $("<div></div>").addClass("box");
$(document).ready(function(){
for(var i = 0; i < 16; i++) {
$("#container").append(box);
}
});
I also tried this within the for loop's code block:
if($("#container:contains(box)")) {
$(box).append(box);
}
I kind of understand why this does not work. That var box is only referencing an element and is not a copy of an element?
As you can likely tell, I'm new. I would really appreciate some pointers on how I can achieve this. Thanks.
Why not just use like this?
for(var i = 0; i < 16; i++) {
$("#container").append('<div class="box box-'+i+'" />');
}
You're appending the same div over and over. That will just move it (in this case, right back where it was). For a new div each time:
$(document).ready(function(){
var ctr = $('#container');
for(var i = 0; i < 16; i++) {
ctr.append("<div class='box'></div>");
}
});
$(document).ready(function() {
var ctr = $('#container');
for (var i = 0; i < 16; i++) {
ctr.append("<div class='box'></div>");
}
});
.box {
margin: 10px;
height: 25px;
width: 25px;
background-color: red;
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container"></div>
I recommend against using append in a loop, bad performance. I suggest this:
var buffer = [];
for(var i = 0; i < 16; i++) {
buffer.push("<div class='box'></div>");
}
var html=buffer.join('');
$('#container').append(html);

Instantiate new element class using javascript

How can I instantiate an existing div element using javascript? Lets say I have:
<div class="container">
<div class="myclass">TROLL FACE</div>
</div>
I want to create as many 'myclass' element inside the 'container' class as I want using javascript. How can I do this?
Please help, thanks.
You may want the .clone method.
var ele = $('.myclass');
for (var i = 0; i < 5; i++) {
ele.clone().appendTo('.container');
}
The live demo.
var container = $('.container');
for (var i = 0; i < 5; i++) {
container.append('<div class="myclass">TROLL FACE</div>');
}
You could use the .append() method.
With or without JQuery:
for (var i = 0; i < howMany; ++i) {
// pure js
var div = document.createElement('div')
div.classList.add('myclass')
somePlace.appendChild(div)
// jquery
$("<div></div>").addClass('myclass').appendTo(somePlace)
}
Try this
<div class="container">
<div class="myclass">TROLL FACE</div>
</div>
var $container = $('.container');
var $myclass = $('.container').html();
var mycount ; // Your count
for(var i =0;i< mycount ; i++){
$container.append($myclass)
}

Categories

Resources