How can I toggle a class to various items? - javascript

I just want to toggle a class from various items. I mean, I have 5 divs with .item class inside a div with .container class. Can I toggle a new class to those 5 .items? Maybe with a loop?
I was trying to do it but it seems that the loop goes infinite.
This is what I tried:
<div class="container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<button onclick="myFunction()"></button>
</div>
<script>
function myFunction () {
var x = document.getElementsByClassName("item");
for (i=0; i<x.length; i+1) {
x[i].classList.toggle('new-class');
}
}
</script>
I expect something like this at the end (maybe with some loop in JS):
<div class="container">
<div class="item new-class"></div>
<div class="item new-class"></div>
<div class="item new-class"></div>
<div class="item new-class"></div>
<div class="item new-class"></div>
</div>

You can do it by using the for loop and the classList.add() method.
function myFunction() {
var items = document.querySelectorAll('.item');
for(var i = 0; i < items.length; i++) {
items[i].classList.add('new-class');
}
}

Related

How can I sort divs with javascript

I would like to sort a few divs in ascending order based on their data-id. How can I do that?
<div class="container" data-id="1000">
<div id="H1"></div>
<div id="sub">sub 1</div>
<div id="sub">sub 2</div>
</div>
<div class="container" data-id="3000">
<div id="H1"></div>
<div id="sub"></div>
<div id="sub"></div>
</div>
<div class="container" data-id="2000">
<div id="H1"></div>
<div id="sub"></div>
<div id="sub"></div>
</div>
I've found the solution to my problem a while ago:
function sortOut() {
// get the classname chapcontainer
var classname = document.getElementsByClassName('container');
// create a variable and put the classes it into an array.
var divs = [];
for (var i = 0; i < classname.length; ++i) {
divs.push(classname[i]);
}
// Sort the divs based on data-id.
divs.sort(function(a, b) {
return +a.getAttribute("data-id") - +b.getAttribute("data-id");
});
};
divs.sort does the trick. More info about this function can be found here:
https://www.w3schools.com/jsref/jsref_sort.asp

Pure JS add class to only one of recurring elements

I'm trying to toggle a div's class in pure javascript (unfortunately I cannot use jQuery). I've got some code working but it doesn't work for multiple instances of the div and I'd appreciate some help for that.
I can't give each element it's own specific ID, so I'd need a way to target only the div with a class of 'truncate' that is the parent of the particular button that is clicked. Currently I have hidden the results by default and am just toggling the 'show' class
<div class="truncate">
<div class="result">Result 1</div>
<div class="result">Result 2</div>
<div id="button">Show more</div>
</div>
collapse= document.getElementById('button');
collapse.onclick = function() {
collapse.parentElement.classList.toggle("show");
};
/* HIDE PLATES BY DEFAULT */
.truncate .result {
display: none;
}
/* SHOW RESULTS WHEN SHOW CLASS APPLIED */
.truncate.show .result {
display: block !important;
}
Thank you - help appreciated as always.
I think you need getElementsByClassName
(function() {
var collapse = document.getElementsByClassName('button');
for (var elIndex = 0; elIndex < collapse.length; elIndex++) {
collapse[elIndex].onclick = function() {
this.parentElement.classList.toggle("show");
};
}
})();
/* HIDE PLATES BY DEFAULT */
.truncate .result {
display: none;
}
/* SHOW RESULTS WHEN SHOW CLASS APPLIED */
.truncate.show .result {
display: block !important;
}
<div class="truncate">
<div class="result">Result 1</div>
<div class="result">Result 2</div>
<div class="button">Show more</div>
</div>
<div class="truncate">
<div class="result">Result 1</div>
<div class="result">Result 2</div>
<div class="button">Show more</div>
</div>
<div class="truncate">
<div class="result">Result 1</div>
<div class="result">Result 2</div>
<div class="button">Show more</div>
</div>
You should replace the id of Show more to class.
And use the following code.
collapse =document.getElementsByClassName('button');
for(let i = 0; i < collapse.length; i++){
let oneElement = collapse[i];
oneElement.addEventListener('click', function() {
oneElement.parentElement.classList.toggle("show");
})
}
Parse (loop over) all of your div.truncate elements and give themselves their own functionality via the Accordionize Function.
const Accordionize = el => {
const results = el.querySelectorAll('.result')
const toggleButton = el.querySelector('button')
let open = false
const _toggle = () => {
const action = open ? 'remove' : 'add'
results.forEach(item => item.classList[action]('show'))
open = !open
}
toggleButton.addEventListener('click', _toggle)
}
// get all div.truncate and apply them to their own instance of Accordionize
document.querySelectorAll('.truncate').forEach(Accordionize)
.truncate {
border: 2px solid red;
margin: 5
}
.result {
display: none;
}
.show {
display: block
}
<div class="truncate">
<div class="result">Result 1</div>
<div class="result">Result 2</div>
<button>Show more1</button>
</div>
<div class="truncate">
<div class="result">Result 3</div>
<div class="result">Result 4</div>
<button>Show more2</button>
</div>
<div class="truncate">
<div class="result">Result 5</div>
<div class="result">Result 6</div>
<button>Show more3</button>
</div>
<div class="truncate">
<div class="result">Result 7</div>
<div class="result">Result 8</div>
<button>Show more4</button>
</div>

Vanilla JS Find Element with Missing Child Element

I am trying to get a boolean that will let me know if a parent element has a child element. Some of the constraints are:
There can be x number of these "boxes"
Check and see for any of the boxes have a footer element
If the box does not have a footer element, add a class
<div class="data-trend">
<header></header>
<div class="main"></div>
<footer></footer>
</div>
<div class="data-trend">
<header></header>
<div class="main"></div>
<footer></footer>
</div>
<div class="data-trend">
<header></header>
<div class="main">
<span class="glyphicons"><span>
<!-- On the glyphicons I would add class if there is no footer -->
</div>
<!-- notice no footer -->
</div>
Moved the above comment into an actual answer:
var elems = document.querySelectorAll('.data-trend'),
len = elems.length,
i = -1
while(++i < len) {
if(!elems[i].querySelector('footer')) elems[i].classList.add('no-footer')
}
.no-footer { border: 3px solid blue; }
<div class="data-trend">
<header>Testing</header>
<div class="main"></div>
<footer>Footer</footer>
</div>
<div class="data-trend">
<header>Testing</header>
<div class="main"></div>
<footer>Footer</footer>
</div>
<div class="data-trend">
<header>Testing</header>
<div class="main">
<span class="glyphicons"><span>
</div>
</div>
If you're doing a lot of this in vanilla, it makes sense to define a forEach helper function for yourself
function forEach(elems, fn){
var len = elems.length,
i = -1
while(++i < len) {
fn(elems[i])
}
}

ReactJs Isotope

Trying to develop a reactjs Isotope component. I've created the core component and been following the masonary link
http://developers.redhat.com/blog/2016/01/07/react-js-with-isotope-and-flux/
I'm getting the error "Unknown DOM property class. Did you mean className?"
//lastet jsfiddle
https://jsfiddle.net/7xzd92s5/54/
var Grid = React.createClass({
getInitialState: function(){
var $container = $('#Isotope2'),
$checkboxes = $('#filters input');
$container.isotope({
itemSelector: '.item'
});
// get Isotope instance
var isotope = $container.data('isotope');
// add even classes to every other visible item, in current order
function addEvenClasses() {
isotope.$filteredAtoms.each( function( i, elem ) {
$(elem)[ ( i % 2 ? 'addClass' : 'removeClass' ) ]('even')
});
}
$checkboxes.change(function(){
var filters = [];
// get checked checkboxes values
$checkboxes.filter(':checked').each(function(){
filters.push( this.value );
});
// ['.red', '.blue'] -> '.red, .blue'
filters = filters.join(', ');
$container.isotope({ filter: filters });
addEvenClasses();
});
$('#shuffle').click(function(){
$container.isotope('shuffle');
addEvenClasses();
});
return null;
},
render: function() {
return ( < div className = "grid" >
<div class="item red"></div>
<div class="item blue"></div>
<div class="item green"></div>
<div class="item yellow"></div>
<div class="item red"></div>
<div class="item blue"></div>
<div class="item green"></div>
<div class="item yellow"></div>
<div class="item red"></div>
<div class="item blue"></div>
<div class="item green"></div>
<div class="item yellow"></div>
<div class="item red"></div>
<div class="item blue"></div>
<div class="item green"></div>
<div class="item yellow"></div>
<div class="item red"></div>
<div class="item blue"></div>
<div class="item green"></div>
<div class="item yellow"></div>
< /div>
);
}
});
ReactDOM.render( < Grid name = "Isotope2" / > , document.getElementById('Isotope2'));
JSX is not exactly the same as HTML. There are some key differences.
In this case, the error message is telling you what's wrong. You need to replace class, which is a reserved JS keyword, with className:
render: function() {
return (
<div className="grid">
<div className="item red"></div>
<div className="item blue"></div>
...etc
</div>
);
}
JSX is alittle bit different than the HTML.
There are few differences that is listed in the DOM differences in React.js.
DOM class attribute is replaced in React with classNamesince class is a JavaScript reserved word.
Since class and for are reserved words in JavaScript, the JSX elements for built-in DOM nodes should use the attribute names className and htmlFor respectively, (eg. ). Custom elements should use class and for directly (eg. ).

grouping nodeList elements into separate Groups

I have following nodeList
['<div class="item">1</div>', '<div class="item">2</div>', '<div class="item">3</div>', '<div class="item">4</div>']
and following function which accepts the number of element for a group and generates group of elements wrapped by divs
function groupElms (nOfElms) {
var count = 0;
[].forEach.call(nL, function (item) {
count++;
});
}
lets say noOfElms is 2 then the function should generate Elements like this
<div>
<div class="item">1</div>
<div class="item">2</div>
</div>
<div>
<div class="item">3</div>
<div class="item">4</div>
</div>
if noOfElms is 3 it should be like
<div>
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
</div>
<div>
<div class="item">4</div>
</div>
I dont understand how to achieve this. Please Could someone help me with this.
You can simply loop through your items and place every N of them into a created wrapper like this:
function groupNodes(list, groupBy)
{
var list = [].slice.call(list);
var parent = list[0].parentElement;
for (var i = 0; i < list.length; i += groupBy)
{
var lastWrapper = document.createElement('div');
lastWrapper.className = 'wrapper';
parent.appendChild(lastWrapper);
[].forEach.call(list.slice(i, i + groupBy), function(x) {
lastWrapper.appendChild(x);
});
}
}
groupNodes(document.getElementsByClassName('item'), 3);
.wrapper {
border: 2px solid black;
}
<div id="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
</div>
Note that it is supposed that all of these items are siblings. Otherwise, they all will be moved to the parent of the first item.
It can be done even easier using jQuery .wrap() function:
function groupNodes(selector, groupBy)
{
var $list = $(selector);
for (var i = 0; i < $list.length; i += groupBy)
$list.slice(i, i + groupBy).wrapAll('<div class="wrapper"></div>');
}
groupNodes('.item', 3);
.wrapper {
border: 2px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
</div>
use the following
lets say
var a = ['<div class="item">1</div>', '<div class="item">2</div>', '<div class="item">3</div>', '<div class="item">4</div>'];
then function should be written like the following
function groupElms (nOfElms) {
var count = 1;
a.forEach(function (item) {
if(count == 1) {
var tempDiv = document.createElement("div");
}
tempDiv.appendChild(item);
if(count == nOfElms) {
document.body.appendChild(tempDiv);
delete tempDiv;
count=1;
}
count++;
});
}

Categories