Get each li value with a specific class name - javascript

Assume I have a body such as;
<div class="body">
<ul>
<li class="01">hi</li>
<li class="02">bye</li>
<li class="03">go</li>
</ul>
<ul style="">
<li class="01">hi2</li>
<li class="02">bye2</li>
<li class="03">go2</li>
</ul>
</div>
I want to get each class = "01", class = "02" and class = "03" values of each ul.
What I did so far?
$('.body ul').each(function(element)
{
console.log(this);
});
It printed the each li element but how can I reach the values in class 01,02 and 03?
I want to get
hi bye go
hi2 bye2 go2
while looping inside the body

Have a look at Selector Documentation.
$("li.02") - for all <li> with class 02
$(".body>ul>li.02") - for all <li> with class 02 inside a <ul>
inside an element with class body.
//for all <li> with class "02"
$('li.02').each(function(element) {
console.log(this.innerHTML);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="body">
<ul>
<li class="01">hi</li>
<li class="02">bye</li>
<li class="03">go</li>
</ul>
<ul style="">
<li class="01">hi2</li>
<li class="02">bye2</li>
<li class="03">go2</li>
</ul>
</div>

$('li.01').text(); returns the string in the element.
If you want to output the strings for each class you can do:
$('li.01').each(function(element) {
console.log($(this).text());
});
and for all list items
$('li').each(function(element) {
console.log($(this).text());
});

Related

add extra class when click on list item, on basis of data-pos name?

<ul id="myList">
<li class="list" data-pos="Noah">pass</li>
<li class="list" data-pos="Liam">fail</li>
<li class="list" data-pos="James">average</li>
</ul>
Now I want to create a JavaScript function that will add new class, when click on it.
click (data-pos="Noah") add class Noah1
click (data-pos="Liam") add class Liam1
click (data-pos="James") add class James1
Expected Result After Click
<ul id="myList">
<li class="list Noah1" data-pos="Noah">pass</li>
<li class="list Liam1" data-pos="Liam">fail</li>
<li class="list James1" data-pos="James">average</li>
</ul>
How can I do that? with JavaScript
var changeFunc -> (e) {
document.getElementById(...).classList.add((this.querySelector(":selected").getAttribute("data-pos") + "1"));
}
document.querySelector(".myList").addEventListener("change",changeFunc);
Here is working solution, just get data-pos attribute and add it to classList
function clickEvent(event) {
event.target.classList.add(event.target.getAttribute('data-pos') + "1")
console.log(event.target.classList)
}
document.querySelector('ul').addEventListener('click', clickEvent, false);
<ul class="myList">
<li class="list" data-pos="Noah">pass</li>
<li class="list" data-pos="Liam">fail</li>
<li class="list" data-pos="James">average</li>
</ul>
One-liner solution:
document.querySelectorAll('ul>li.list').forEach(li=>{li.onclick=function(){const attr=li.getAttribute('data-pos');if(!(attr in li.classList))li.classList.add(attr);}});

getting last item in an each() loop

I'm struggling to understand how to get the last item in an each() loop. I asked a question last week on this topic, which can be seen here: .find() relationship with loops, each() and this keyword - .find() returning 4 when it should only be 2
The original requirement was to check a series of uls inside uls, and if there were more than 1 lists I need to add a class. Now - I need to build upon this code where if there are more than three lists inside a div, or it is the last ul in a series, I need to add a class to the last ul as well.
I did research on the topic and will be referencing this answer: Last element in .each() set
For reference, the first sample case is below:
$(function(e) {
var getMenuItems = $(".item");
getMenuItems.each(function( index ) {
if ($(this).find("ul.sub-menu").length > 0) {
$(this).addClass("red");
}
});
});
.red {background-color: red;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li class="item">
<ul class="sub-menu">
<li></li>
</ul>
</li>
<li class="item">
</li>
<li class="item">
<ul class="sub-menu">
<li></li>
</ul>
</li>
<li class="item">
</li>
</ul>
This code just checks if there are more than 1 lists inside a div and if there are add a class.
Now the next step is to not only add a class to the divs with more than 1 list but the last ul in the series irregardless of amount of lists. The answer Last element in .each() set suggests to simply cross reference index and see if you are at the last item.
The highest upvoted answer says to:
Check index against the length of the set and you're good to go:
That concept integrated into my sample looks like this:
$(function(e) {
var getMenuItems = $(".item");
var howManyListItems = getMenuItems.length;
getMenuItems.each(function( index ) {
if ($(this).find("ul.sub-menu").length > 0) {
$(this).addClass("red");
} else if (index == (howManyListItems.length - 1)) {
console.log($(this));
$(this).addClass("red");
}
});
});
.red {background-color: red;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li class="item">
<ul class="sub-menu">
<li></li>
</ul>
</li>
<li class="item">
</li>
<li class="item">
<ul class="sub-menu">
<li></li>
</ul>
</li>
<li class="item">
</li>
<li class="item">
</li>
<li class="item">
</li>
<li class="item">
</li>
</ul>
The expected/desired behavior is to add the red to the last item but sadly that does not happen.
As can be seen as a troubleshooting measure, console logging this into that conditional returns nothing. So is that not the last item of the array? How would you modify it/target it? What does that conditional represent? Since console logging does nothing, how does one go about troubleshooting this code?
How do you hit the last element in an each loop and modify it's DOM properties?
This is as easy as:
$(function(e) {
$(".sub-menu:last-of-type").last().addClass("red");
});
.red {background-color: red;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li class="item">
<ul class="sub-menu">
<li></li>
</ul>
</li>
<li class="item">
</li>
<li class="item">
<ul class="sub-menu">
<li></li>
</ul>
</li>
<li class="item">
</li>
<li class="item">
</li>
<li class="item">
</li>
<li class="item">
</li>
</ul>

Show first level children of a nested ul li using jquery

I have an HTML file like this:
JS:
function functionName(event) {
event.stopPropagation();
var item = event.data.param;
document.getElementById("list").innerHTML = item;
}
$(document).ready(function() {
$("li").each(function() {
$(this).on('click', {param: this.id}, functionName);
});
});
HTML:
<div id="main">
<div id="tree">
<ul class="xyz">
<li class="hide">AVC</li>
<li class="hide">Anna</li>
<li class="hide">Peter</li>
<li id="foo1">Gary
<ul class="xyz">
<li class="hide">John</li>
<li class="hide">Anna</li>
<li id="foo2">Briton
<ul class="xyz">
<li class="hide">gg</li>
<li class="hide">hh</li>
<li id="foo3">Layla
<ul class="xyz">
<li class="hide">gg</li>
<li class="hide">hh</li>
<li id="foo4">Undertaker
<ul class="xyz">
<li class="hide">gg</li>
<li class="hide">hh</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div id="list"></div>
</div>
I have two div tags whose id is receptively tree and list. Tree div contains the nested ul li tags and each li have unique id.
I want to show the first level children of a ul li tag. For example, when I am clicking on Gary, it should show the first level children ( John, Anna, Britton) in right div i.e. list.
Right now I am able to get the id of ul li element in list div when clicking any item.
How can I traverse the first level children of clicking element using jquery/javascript and display them in list div?
Thanks
Try using find() ,> ul selects the direct descendant
$('li[id^="foo"]').click(function(e){
e.stopPropagation();
var x = $(this).last().find(' > ul').clone().find('ul').remove().end();
console.log(x[0])
$('#list').html(x);
$('#list .hide').show();
});
simple demo : https://jsfiddle.net/sk30mwud/4/
'$('#tree').on('click', 'li', function(){
$(this).find('> ul > li').toggleClass('hide');
return false;
})'
Can you please take a look at this approach:
It uses .contents().get(0).nodeValue to fetch the text present in child li nodes and not from its childerns if any.
function functionName(event) {
event.stopPropagation();
var item = event.data.param;
var names = [];
$("#" + item).children("ul").children("li").each(function() {
names.push($(this).contents().get(0).nodeValue);
});
$("#list").text(names.join(","));;
}
$(document).ready(function() {
$("li").each(function() {
$(this).on('click', {
param: this.id
}, functionName);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="main">
<div id="tree">
<ul class="xyz">
<li class="hide">AVC</li>
<li class="hide">Anna</li>
<li class="hide">Peter</li>
<li id="foo1">Gary
<ul class="xyz">
<li class="hide">John</li>
<li class="hide">Anna</li>
<li id="foo2">Briton
<ul class="xyz">
<li class="hide">gg</li>
<li class="hide">hh</li>
<li id="foo3">Layla
<ul class="xyz">
<li class="hide">gg</li>
<li class="hide">hh</li>
<li id="foo4">Undertaker
<ul class="xyz">
<li class="hide">gg</li>
<li class="hide">hh</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div id="list"></div>
</div>

Remove the class of one element and assign it to another using JavaScript

I need to remove the selected class of an <a> and assign it the last <a> instead. Both are nested within individual <li> elements.
Here's an example of the code:
<ul class="tabs clearfix">
<li class="tab">Home</li>
<li class="tab">About</li>
<li class="tab">Profile</li>
<li class="tab">History</li>
<li class="tab">The Beginning of V-Cube</li>
</ul>
How can I achieve this using JavaScript/jQuery? Please advise.
EDIT:
Let's say I don't want to target the last tab specifically. Can the href be used as a selector instead?
EDIT #2:
Thank you so much everyone for the quick response. All your answers were spot on, wish I could mark them all as answers :)
To remove class from an element, use removeClass.
To get the last element, use :last selector or last(). To add new class to element use addClass
$('.selected').removeClass('selected');
$('.tabs li:last a').addClass('selected');
// OR
// $('.tabs li').last().children('a').addClass('selected');
.selected {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="tabs clearfix">
<li class="tab">Home
</li>
<li class="tab">About
</li>
<li class="tab">Profile
</li>
<li class="tab">History
</li>
<li class="tab">The Beginning of V-Cube
</li>
</ul>
Update
Let's say I don't want to target the last tab specifically. Can the href be used as a selector instead?
$('.tabs a[href="#five"]').addClass('selected');
Try this.
$(".tabs li").first().find("a").removeClass("selected");
$(".tabs li").last().find("a").addClass("selected");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="tabs clearfix">
<li class="tab">Home</li>
<li class="tab">About</li>
<li class="tab">Profile</li>
<li class="tab">History</li>
<li class="tab">The Beginning of V-Cube</li>
</ul>
Try this:
$(document).ready(function(){
var classname = $(".tabs li:first-child a").attr("class");
console.log(classname);
$(".tabs li:last-child a").addClass(classname);
$(".tabs li:first-child a").removeClass();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<ul class="tabs clearfix">
<li class="tab">Home</li>
<li class="tab">About</li>
<li class="tab">Profile</li>
<li class="tab">History</li>
<li class="tab">The Beginning of V-Cube</li>
</ul>
it is quite easy also in vanilla JS:
document.querySelector('.selected').classList.remove('selected');
document.querySelector('.tabs li:last a').classList.add('selected');
If you want to use an arbitrary a and select the attribute href then you should use this selector:
a[href="HREFVALUE"]
$('.clearfix').find('.selected').removeClass('selected');
$('.clearfix').find('li:last').find('a').addClass('selected');
$("a[href$='five']").addClass('bold');
.selected {
color: red
}
.bold {
font-weight: bold
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="tabs clearfix">
<li class="tab">Home
</li>
<li class="tab">About
</li>
<li class="tab">Profile
</li>
<li class="tab">History
</li>
<li class="tab">The Beginning of V-Cube
</li>
</ul>
Just use .removeClass() and .addClass()
.removeClass()
Remove a single class, multiple classes, or all classes from each element in the set of matched elements.
.addClass()
Description: Adds the specified class(es) to each element in the set of matched elements.

jquery ordering and group li elements

Let's say I have a list of items under a div or UL. I want to take all the list items with the same title attribute and wrap a UL around it. The next part though is that I want that UL to be under the LI with the same attribute. So, I'm trying to group basically.
So.... I start with.....
<li>Insurance</li>
<li>Education</li>
<li>Sports</li>
<li>Construction</li>
<li title ="Insurance">Malpractice</li>
<li title ="Construction">Carpentry</li>
<li title ="Education">College</li>
<li title ="Insurance">Automobile</li>
<li title ="Education">High School</li>
<li title ="Construction">Iron Worker</li>
and I want to get to......
<li>Insurance
<ul>
<li title ="Insurance">Malpractice</li>
<li title ="Insurance">Automobile</li>
</ul>
</li>
<li>Education
<ul>
<li title ="Education">College</li>
<li title ="Education">High School</li>
</ul>
</li>
<li>Sports</li>
<li>Construction
<ul>
<li title ="Construction">Carpentry</li>
<li title ="Construction">Iron Worker</li>
</ul>
</li>
Any help would be appreciated. Obviously new to the jquery and javascript world so I'm trying to wrap my brain around this.
Input:
<div id="stuffs">
<li>Insurance</li>
<li>Education</li>
<li>Sports</li>
<li>Construction</li>
<li title ="Insurance">Malpractice</li>
<li title ="Construction">Carpentry</li>
<li title ="Education">College</li>
<li title ="Insurance">Automobile</li>
<li title ="Education">High School</li>
<li title ="Construction">Iron Worker</li>
</div>
jQuery:
​$("#stuffs li").each(function(){
$("#stuffs li[title='"+$(this).text()+"']").appendTo($(this)).wrapAll("<ul />");
});​​​​​​​​​​
Output:
<div id="stuffs">
<ul>
<li>Insurance
<ul>
<li title="Insurance">Malpractice</li>
<li title="Insurance">Automobile</li>
</ul>
</li>
<li>Education
<ul>
<li title="Education">College</li>
<li title="Education">High School</li>
</ul>
</li>
<li>Sports</li>
<li>Construction
<ul>
<li title="Construction">Carpentry</li>
<li title="Construction">Iron Worker</li>
</ul>
</li>
</ul>
</div>
Smile :-)
Demo here
// first we fetch all items without title attribute
var topLevel = $('li:not([title])');
// for each of those...
topLevel.each(function() {
var li = $(this),
// ... we get its text ...
title = li.text(),
// ... and other li elements with the corresponding title
children = $('li[title="' + title + '"]');
// if there are any...
if (children.length > 0) {
// ... create an empty list ...
var ul = $('<ul></ul>');
// ... fill it and ...
children.appendTo(ul);
// ... append it to the original li element
ul.appendTo(li);
}
});
jQuery documentation: :not(), [title], each(), appendTo()
This should work
$('#id li:not([title])').append('<ul />');
$('#id li[title]').each(function() {
$(this).appendTo('#id li:contains(' + $(this).attr('title') + ') ul');
})
A demo

Categories