QuerySelectorAll returns more than expected - javascript

<div class="main">
<p>I don't want this</p>
<div class="sub">I want this</div>
</div>
<div class="main">
<p>I don't want this</p>
<div class="sub">I want this</div>
</div>
<div class="main">
<p>I don't want this</p>
<div class="sub second">I don't want this</div>
</div>
Im trying to use QuerySelectorAll to return all "sub" divs nested inside "main" divs. Im currently using
document.querySelectorAll(".main .sub")
but this returns all divs that class name begins with "sub" so it also return divs with the class name "sub second" or "sub third" is it possible to just select divs thats class are "sub".
I also want to click on the results after using
document.querySelectorAll(".main .sub").click()
but this returns an error i think this is becasue
.click()
is only designed to work with one object at a time. Is it possible to select all divs with the class name "sub" and then click on them using something similar to
.click()

You can use this selector:
document.querySelectorAll(".main [class='sub']")
You can iterate over result items as follows:
var divs = document.querySelectorAll(".main [class='sub']");
[].forEach.call(divs, function(div) {
// do whatever
div.style.color = "red";
});
<div class="main">
<p>I don't want this</p>
<div class="sub">I want this</div>
</div>
<div class="main">
<p>I don't want this</p>
<div class="sub">I want this</div>
</div>
<div class="main">
<p>I don't want this</p>
<div class="sub second">I don't want this</div>
</div>

Look at the accepted answer here: Fastest way to convert JavaScript NodeList to Array?
Array.prototype.slice.call(document.querySelectorAll(".main .sub")).forEach(function(el){
el.click();
})
EDIT 1 - Timeout
To timeout between each click, simple add a setTimeout call within a closed scope, reference the iteration and multiply with the desired delay:
Array.prototype.slice.call(document.querySelectorAll(".main .sub")).forEach(function (el, i) {
(function (a) {
setTimeout(function () {
el.click();
}, (10 * 1000) * a);
})(i);
})

Related

How to expand and collapse multiple divs, without repeating the same code using jQuery

I want to write a code that expands and collapses a div with a paragraph, once you click the header text above it.
<div class="container">
<h3><span class="toggler">Text that toggles</span></h3>
<div class="wrapper">
<p>Random text</p>
</div>
</div>
<div class="container">
<h3><span class="toggler2">Text that toggles</span></h3>
<div class="wrapper2">
<p>Random text</p>
</div>
</div>
I am aware that I could write a function like this which would toggle between display: block and display: none.
I could just repeat the same function for different divs with different classes and it would work, but if I have a lot of them I would end up repeating the same function multiple times and I feel like there has to be a much cleaner way to do this.
$(document).ready(function() {
$(".toggler").on("click", function() {
$(".wrapper").toggleClass("active");
});
});
You don't need write single line of code if you use jquery & bootstrap.
Solution 1:
Add reference bnelow:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
your html:
<div class="container">
<h3><span class="toggler" data-toggle="collapse" data-target="#col1">Text that toggles</span></h3>
<div class="wrapper" id="col1">
<p>Random text</p>
</div>
</div>
<div class="container">
<h3><span class="toggler2" data-toggle="collapse" data-target="#col2">Text that toggles</span></h3>
<div class="wrapper2" id="col2">
<p>Random text</p>
</div>
</div>
Solution 2:
Either you can write simple line code
$(document).ready(function() {
$("h3").on("click", function() {
$(this).next().toggleClass("active");
});
});
we can select header with header Tag. After that, we can add toogleClass to just next element that is "DIV".
so, when click header, toggleClass will be added to next element that is DIV
You dont need to repeat it, give both a single class like "toggle-enabled" then instead of using toggler and toggler2 as two function you can put toggle-enabled as one selector and both will run the same function on click.
If you want to only toggle the one selected then use "this" keyword to get current and hide and show that or slide it whatever you want to do but dont need to repeat the code.
Here is your example code working as expected:
$(document).ready(function() {
$(".toggle-enabled").on("click", function() {
var nextdiv = $(this).parent().siblings("div");
nextdiv.is(":visible")?nextdiv.hide():nextdiv.show();
});
});
.togglethis{color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h3><span class="toggler toggle-enabled">Text A that toggles</span></h3>
<div class="wrapper togglethis">
<p>Random text</p>
</div>
</div>
<div class="container">
<h3><span class="toggler2 toggle-enabled">Text B that toggles</span></h3>
<div class="wrapper2 togglethis">
<p>I have left your toggler2 class in there and you can add more classes to separate it</p>
</div>
</div>
This code should work for your html:
$(document).ready(function () {
$('[class^="toggler"]').on('click', function () {
$(this).closest('.container').children('[class^="wrapper"]').toggle();
});
});
The code looks for any element on your html whose class name starts with toggle. It then attaches an on-click handler function. That function then looks for the affected element's closest ancestor with class name of container. Then from that ancestor/parent, it selects children with class name starting with wrapper. It then toggles the visibility of those children (or child)
You could give your togglers class names of toggleN (where N is any valid class name character) or simply toggle (same class name for all). Similarity, you could name the classes for your wrappers as wrapperN or simply wrapper.

Show multiple divs

so, I'm working on a project that has 2 tables in database that are related!
I need via JavaScript Hide and Show the divs containing the right information.
I got a main product Stone, and each Stone has 2 other Stone Types
So if I click on the img that has Stone1, I want to show Stone1.1, Stone1.2, etc and hide all the other StoneTypes.
This is what I got now on JS
jQuery('.Pedras').click(function(){
jQuery('.SubPedras').hide();
jQuery('#div'+$(this).attr('target')).show();
});
The problem here is that I only get the first div to show, eventhough I have 2 divs with the same Name example:
<div id="div{IdPedra}" class="SubPedras">
<div id="div{IdPedra}" class="SubPedras">
<div id="div{IdPedra}" class="SubPedras">
And {IdPedra} Is the id of the stone in the database, so I will get "div1" two or 3 times, etc.
Can anyone pls help me, I'm not able to find a suitable solution for my need.
Thank you!
You could use data-attributes to accomplish this. In your change my code to;
<div data-id="{IdPedra}" class="SubPedras">Stone 1.1</div>
<div data-id="{IdPedra}" class="SubPedras">Stone 1.2</div>
<div data-id="{IdPedra}" class="SubPedras">Stone 2.1</div>
<div data-id="{IdPedra}" class="SubPedras">Stone 2.2</div>
You can access an element's data-attribute by using $(element).data("name"); this is equivalent to data-name. I also stored the Pedras
Loop through the SubPedras and check if they match the button where the parent category or value you wish to use as filter. Run the snippet, thanks!
(You could also store them to class attribute instead of data)
jQuery('.Pedras').click(function() {
// store button value to variable
var pedraValue = $(this).val();
// loop through the SubPedras
$(".SubPedras").each(function() {
// get the value from data attribute
if ($(this).data("id") == pedraValue) {
// if match show
$(this).show();
}
else{
// else hide
$(this).hide();
}
});
});
.SubPedras{
line-height:40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-id="Stone1" class="SubPedras">Stone 1.1</div>
<div data-id="Stone1" class="SubPedras">Stone 1.2</div>
<div data-id="Stone2" class="SubPedras">Stone 2.1</div>
<div data-id="Stone2" class="SubPedras">Stone 2.2</div>
<button class="Pedras" value="Stone1">Stone 1</button>
<button class="Pedras" value="Stone2">Stone 2</button>

Dragula drop in multiple divs

I implemented drag 'n' drop on my application using Dragula, but I need to set it so I can drop my elements to more than one div.
I tried to use a class to achieve it, but it just activates the first one of my divs.
THe HTML:
<div role="presentation" class="table table-striped">
<div class="files" id="upload-file"></div>
</div>
<div class="col-md-4">
<div class="drag-container">Test 1</div>
<div class="drag-container">Test 2</div>
<div class="drag-container">Test 3</div>
</div>
The JS calling Dragula:
dragula([document.querySelector('#upload-file'), document.querySelector('.drag-container')]);
How can I drop te items to more than one div?
You can define an array containers:
var containers = $('.drag-container').toArray();
containers.concat($('#upload-file').toArray());
And then, pass the var 'containers' to dragula initializer:
dragula(containers, {
isContainer: function (el) {
return el.classList.contains('drag-container');
}
});
For those without jQuery or $ you can use:
dragula([].slice.call(document.querySelectorAll("drag-container")));
This converts the NodeList to an array and passes it to dragula.
querySelector only returns a single element, you would need to use querySelectorAll in order to get a list of elements. Not sure how dragula would handle getting a two element array, with the second element being an array. You may want to generate the array first, add the '#upload-file' to that array, and then pass the array. Or you could generate the array after initializing, and cycle through the array, adding the elements dynamically using something like "drake.containers.push(container);". I got this construct directly from the github site https://github.com/bevacqua/dragula
HTML:
<div className="wrapper">
<div className="container col-md-4" id="A">
<div className="panel panel-white">
</div>
<div className="panel panel-white">
</div>
</div>
<div className="container col-md-4" id="B">
<div className="panel panel-white">
</div>
<div className="panel panel-white">
</div>
</div>
</div>
JS:
dragula([document.querySelector('#A'), document.querySelector('#B')]);
You can drag each item in one column to the other. You can add more columns with the class name of container.
If you want to specify a custom class name, you should define option like this :
Option:
let options = {
isContainer: (el) => {
return el.classList.contains('drag-container'); // The immediate elements in this container will be draggable
}

combine html paragraphs using javascript

I'm currently struggling on a very simple javascript task, but I'm new to it, so its confusing me a lot.
e.g. html
<div class="item">
<div class="title">Item 1 Title</div>
<div class="description-1">lorum</div>
<div class="description-2">ipsum</div>
<div class="description-combined"></div>
</div>
So I need to combine paragraphs 1 & 2, and replace the empty info in paragraph 3. I don't use jQuery yet, so my research has caused struggle because of this.... i currently have:
var p1 = getElementsByClassName ('description-1').innerHTML;
var p2 = getElementsByClassName ('description-2').innerHTML;
var p3 = p1 + P2
document.getElementsByClassName ('description-combined').innerHTML = p3
I did have p3 to have p1.concat(p2) but that didn't work. I'm using it as an external file, so i may be missing out on putting something in my HTML file too.
The edit changes the question.
What I'd probably do is loop through the .item elements, combining the descriptions within.
document.getElementsByClassName is a property of document, not a freestanding function, and it returns a list of matching elements. It's also not as widely supported as document.querySelector and document.querySelectorAll, so I'd probably use those; for what we're talking about, we'll also want Element#querySelector.
// Get a list of the items and loop through it
Array.prototype.forEach.call(document.querySelectorAll(".item"), function(item) {
// Get the two description divs, and the combined, that
// are *within* this item
var d1 = item.querySelector(".description-1");
var d2 = item.querySelector(".description-2");
var c = item.querySelector(".description-combined");
// Set the combined text (this assumes we have them all)
c.innerHTML = d1.innerHTML + d2.innerHTML;
});
.description-combined {
color: green;
}
<div class="item">
<div class="title">Item 1 Title</div>
<div class="description-1">One description 1</div>
<div class="description-2">One description 2</div>
<div class="description-combined"></div>
</div>
<div class="item">
<div class="title">Item 2 Title</div>
<div class="description-1">2 description 1</div>
<div class="description-2">2 description 2</div>
<div class="description-combined"></div>
</div>
<div class="item">
<div class="title">Item 3 Title</div>
<div class="description-1">3 description 1</div>
<div class="description-2">3 description 2</div>
<div class="description-combined"></div>
</div>
The Array.prototype.forEach.call(list, function() { ... }); thing is a way to loop through anything that's like an array, but isn't an array. It's explained more in this other answer, which also has several alternatives.

Append a div to a new div

i am using IPB and i am going to put each category into a new tab the category div is something like this:
<div id='category_100'>
<div id='category_104'>
<div id='category_102'>
<div id='category_101'>
and my tabs content is like this:
<div class="content">
<div id="content-1" class="content-1">
</div>
</div>
and the categories divs is already showing but i want it to be moved to the content-1 div without duplicate so i want it to move from its div to this div with jjava script how?
<script>
document.getElementById('content-1').appendChild(
document.getElementById('category_100')
);
</script>
this worked for me but how can i add more than id to category_100
i want it to be like this in one script code so i would not repeart the scrip code four times:
<div class="content">
<div id="content-1" class="content-1">
<div id='category_100'>
<div id='category_104'>
<div id='category_102'>
<div id='category_101'>
</div>
</div>
using my two lines the suggested things here is not working!
Try this code :
$('div[id^="category_"]').appendTo('#content-1')
Have a look to this fiddle : http://jsfiddle.net/lulu3030/sjEPx/2/
"using my two lines the suggested things here is not working!"
You just get a single element with an ID and trying to append it...
Live Demo
If you want to append multiple elements, there are many ways...
Wrap those elements and then append...
<div id="categories">
<div id='category_100'></div>
<div id='category_104'></div>
<!-- etc. -->
</div>
document.getElementById('content-1').appendChild(document.getElementById('categories'));
or add same class to all elements that you want to append...
<div id='category_100' class="myClass"></div>
<div id='category_104' class="myClass"></div>
[].forEach.call(document.getElementsByClassName("myClass"), function (value, index, array) {
document.getElementById("content-1").appendChild(value);
});
or get elements with query selector that match some pattern...
[].forEach.call(document.querySelectorAll("div[id^='category_']"), function (value, index, array) {
document.getElementById("content-1").appendChild(value);
});
and etc.

Categories

Resources