jQuery: Find occurence/position of class on page - javascript

I am trying to find the occurence/position of a clicked class on the page.
HTML:
<div class="myclass"></div> <!-- OCCURENCE #1 -->
<div class="myclass"></div> <!-- OCCURENCE #2 -->
<div class="myclass"></div> <!-- OCCURENCE #3 -->
<div class="myclass"></div> <!-- OCCURENCE #4 -->
<div class="myclass"></div> <!-- OCCURENCE #5 -->
<div class="myclass"></div> <!-- OCCURENCE #6 -->
jQuery:
$('.myclass').click(function(event) {
//OUTPUT 'This class is the X one on the page'
});
For example if I click on the class occurence #3, I want to know that this class is the 3rd one on the page. I dont want to add any other infos such as data-id or id tag. How can I do that using jQuery? I know that I can get the total number of time the class is found using .length but that's about it.

You should use .index():
$(".myclass").click(function(e) {
var index = $(".myclass").index(this) + 1;
});
DEMO: http://jsfiddle.net/gdcQv/

Related

Add and remove class on multiple element when clicked

I have the below as an example of what I'm working on; I'm trying to add a class to two elements when one of the elements is clicked.
<div id="main">
<div id="section1">
- contents here -
</div>
<div id="section2">
- contents here -
</div>
<div id="section3">
- contents here -
</div>
<div class="plans-group">
<div class="plans-columns plans-type-1">
<div class="plans-col plans-left plans-heading">Heading</div>
<div class="plans-col plans-right">
<div class="select-plan select-gold">Gold</div>
</div>
<!-- end plans-right -->
</div>
<!-- end plans-columns -->
<div class="plans-columns plans-type-2">
<div class="plans-col plans-left plans-heading">Heading</div>
<div class="plans-col plans-right">
<div class="select-plan select-silver">Silver</div>
</div>
<!-- end plans-right -->
</div>
<!-- end plans-columns -->
<div class="plans-columns plans-type-3">
<div class="plans-col plans-left plans-heading">Heading</div>
<div class="plans-col plans-right">
<div class="select-plan select-bronze">Bronze</div>
</div>
<!-- end plans-right -->
</div>
<!-- end plans-columns -->
</div>
<!-- end plans-group -->
</div>
<!-- end main -->
#1): DIV with class "select-plan"
When div with class "select-plan" is clicked, add class "clicked" to that div. When it's clicked again, remove the added class.
#2): DIV with id "main"
When "select-plan" is clicked (as explained above) also add class to the container div with id "main". And remove the added class when "select-plan" is clicked again.
This is where I have a problem because different classes have to be added to "main". For example:
When "select-gold" is clicked, add class "gold-selected" to "main"
When "select-silver" is clicked, add class "silver-selected" to "main"
When "select-bronze" is clicked, add class "bronze-selected" to "main"
I don't want previously clicked div to have its added class removed because another div is clicked. The added class should only be removed when that same div is clicked for the second time and so on...
Also, I might have up to 8 or more plans. The solution should not be limited to the 3 plans (Gold, Silver, and Bronze). I should have the ability to create more plans.
I really appreciate everyone's help with this.
Thanks in advance.
let selectPlan = document.querySelectorAll('.select-plan');
let mainDiv = document.getElementById('main');
selectPlan.forEach(el =>{
el.addEventListener('click',function(e){
if(e.target.classList.contains('select-plan')){
e.target.classList.toggle('clicked');
}
if(e.target.classList.contains('select-gold')){
mainDiv.classList.add('gold-selected');
mainDiv.classList.remove('silver-selected');
mainDiv.classList.remove('bronze-selected');
}else if(e.target.classList.contains('select-silver')){
mainDiv.classList.add('silver-selected');
mainDiv.classList.remove('gold-selected');
mainDiv.classList.remove('bronze-selected');
}else{
mainDiv.classList.add('bronze-selected');
mainDiv.classList.remove('silver-selected');
mainDiv.classList.remove('gold-selected');
}
});
});
let main = document.getElementById("main");
let select = document.querySelector(".select-plan");
let selectG = document.getElementsByName("gold");
let selectS = document.getElementsByName("silver");
let selectB = document.getElementsByName("bronze");
function toggleGold() {
if (main.classList.contains('gold-select')) {
main.classList.remove('gold-select');
} else {
main.classList.add('gold-select');
}
selectG[0].classList.toggle('cliqué')
}
//You can add same function for silver and bronze
document.querySelector(".select-gold").addEventListener("click", toggleGold);
document.querySelector(".select-silver").addEventListener("click", toggleSilver);
document.querySelector(".select-bronze").addEventListener("click", toggleBronze)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div name="gold" class="select-plan select-gold">Gold</div>
<div name="silver" class="select-plan select-silver">Silver</div>
<div name="bronze" class="select-plan select-bronze">Bronze</div>

How to add a unique id to first of kind

ok. Building out a employee directory. At the top of the directory is the alphabet so you can click on a letter an arrive at the first person who has that letter as first letter of last name. How can i loop through the all of the employees and add an id of the letter to the first of each. I haven't built out the markup, yet, but for now it could be as simple as
<h3><span class="fname">Johnny</span><span class="lname">Willis</span></h3>
</div> ```
Where I would target the last name and add an ID to the card
I am pulling all of the content in from a hubspot hubdb. Unsure if that is relevant, but wanted to add that.
I think you don't need to add an ID to each of the last names from your list. If you just want to scroll down to the first item when clicking the alphabet index, try this:
HTML
<!-- A container for the alphabet letters -->
<div id="alphabet">
<span id="letter-a">A</span>
<span id="letter-b">B</span>
<span id="letter-c">C</span>
<span id="letter-d">D</span>
</div>
<!-- A container for each last name -->
<div id="employee-a" style="height:500px">
<p>A</p>
<p>Adams Mike</p>
<p>Addison John</p>
<p>Adkins Smith</p>
</div>
<div id="employee-b" style="height:500px">
<p>B</p>
<p>Bain Chris</p>
<p>Barker Travis</p>
<p>Banner Brock</p>
</div>
<div id="employee-c" style="height:500px">
<p>C</p>
<p>Carl Steve</p>
<p>Carter Aaron</p>
<p>Castle Vania</p>
</div>
<div id="employee-d" style="height:500px">
<p>D</p>
<p>Daenerys Targaryen</p>
<p>Dale Denton</p>
<p>Daniels Jack</p>
</div>
JAVASCRIPT
<script>
// Wait until DOM is fully loaded
$(document).ready(function() {
// Get the ID name from the letter you clicked
$('#alphabet > span').on('click', function() {
// Pass this ID name to a variable
var letter = $(this).attr('id');
var goTo = letter.split('-').pop();
// Use it to smooth scroll to the position of the first last name with the letter you clicked
$('html, body').animate({
scrollTop : $('#employee-' + goTo).offset().top
}, 500);
})
});
</script>
Hope this helps.
Enjoy!

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.

Select specific html tags from a liste of html tag via a jquery or spath selector

With this html structure :
...
<div class="a">April 2018</div>
<div class="b">Monday 02</div>
<div class="c">...</div> <!-- I want get this tag (and its children) -->
<div class="c">...</div> <!-- I want get this tag (and its children) -->
<div class="c">...</div> <!-- I want get this tag (and its children) -->
<div class="c">...</div> <!-- I want get this tag (and its children) -->
<div class="d">...</div>
<div class="b">Monday 02</div>
<div class="c">...</div> <!-- I don't want get this tag ! -->
<div class="c">...</div> <!-- I don't want get this tag ! -->
<div class="c">...</div> <!-- I don't want get this tag ! -->
<div class="c">...</div> <!-- I don't want get this tag ! -->
<div class="d">...</div> <!-- I don't want get this tag ! -->
<div class="b">Monday 02</div>
<div class="c">...</div> <!-- I don't want get this tag ! -->
<div class="c">...</div> <!-- I don't want get this tag ! -->
...
I want save in an array the list of the first div elements with the class "c" before the first div element with the class "d". How can I do that via a jquery selector or an xpath selector ? I don't find how do..
Thank you :)
You can use .prevAll()
Use .eq() to select the first element with class d then .prevAll() to get all previous element with class c
$('.d').eq(0).prevAll('.c').css('color','red')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="a">April 2018</div>
<div class="b">Monday 02</div>
<div class="c">...</div> <!-- I want get this tag (and its children) -->
<div class="c">...</div> <!-- I want get this tag (and its children) -->
<div class="c">...</div> <!-- I want get this tag (and its children) -->
<div class="c">...</div> <!-- I want get this tag (and its children) -->
<div class="d">...</div>
<div class="b">Monday 02</div>
<div class="c">...</div> <!-- I don't want get this tag ! -->
<div class="c">...</div> <!-- I don't want get this tag ! -->
<div class="c">...</div> <!-- I don't want get this tag ! -->
<div class="c">...</div> <!-- I don't want get this tag ! -->
<div class="d">...</div> <!-- I don't want get this tag ! -->
<div class="b">Monday 02</div>
<div class="c">...</div> <!-- I don't want get this tag ! -->
<div class="c">...</div> <!-- I don't want get this tag ! -->
Use prevAll to find previous div with class c before your d class.
$('.d:first').prevAll("div.c").each(function (index, element) {
console.log($(this).html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="a">April 2018</div>
<div class="b">Monday 02</div>
<div class="c">1.I want get this tag (and its children)</div>
<!-- I want get this tag (and its children) -->
<div class="c">2.I want get this tag (and its children)</div>
<!-- I want get this tag (and its children) -->
<div class="c">3.I want get this tag (and its children)</div>
<!-- I want get this tag (and its children) -->
<div class="c">4.I want get this tag (and its children)</div>
<!-- I want get this tag (and its children) -->
<div class="d">...</div>
<div class="b">Monday 02</div>
<div class="c">...</div>
<!-- I don't want get this tag ! -->
<div class="c">...</div>
<!-- I don't want get this tag ! -->
<div class="c">...</div>
<!-- I don't want get this tag ! -->
<div class="c">...</div>
<!-- I don't want get this tag ! -->
<div class="d">...</div>
<!-- I don't want get this tag ! -->
<div class="b">Monday 02</div>
<div class="c">...</div>
<!-- I don't want get this tag ! -->
<div class="c">...</div>
<!-- I don't want get this tag ! -->
You can get this by using $.each for each div
var arr = [];
$(document).ready(function(){
$('div').each(function() {
if ($(this).hasClass('c')) {
arr.push($(this).html());
}
if ($(this).hasClass('d')) {
return false;
}
});
});
here's an option without jQuery :
use querySelector(".d")[0] to get the first div with className d , and loop through the previous divs using previousSibling until the className is different than c then break;
let wantedDivs = [];
let element = document.querySelectorAll('.d')[0];
while(element = element.previousElementSibling){
if(element.className != "c")
break;
else
wantedDivs.push(element);
}
console.log(wantedDivs);

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