How can I change span text inside another span? - javascript

I am trying to make a collapsible list that changes from a '+' to a '-' and back depending upon whether the list is collapsed or expanded. I can get to the text using this statement:
$(this).children().eq(i).children('span')[0].firstChild.outerText;
But I cannot figure out how to change the value. There's probably a more elegant solution that a JQuery Guru can show me. Here is my JSFiddle.
This answer is the closest answer I could find to my question but I don't know how to implement it or even if there is a better way.

This can be simplified quite a bit. Rather than trying to match index, just use jQuery's find() method to target descendants:
$('#test > li').click(function() {
var $symbol = $(this).find('.symbol');
$(this).find('ul').slideToggle('fast');
if ($symbol.text() === ' +') {
$symbol.text(' -');
} else {
$symbol.text(' +');
}
});
.hideUnorderedList {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<ul id="test">
<li id="first">
<span class="Collapsable"><span class="symbol"> +</span>First One</span>
<ul id="myfirstlist" class="hideUnorderedList">
<li>Something to do</li>
<li>Something else to do</li>
</ul>
</li>
<li id="second">
<span class="Collapsable"><span class="symbol"> +</span>Second One</span>
<ul id="mysecondlist" class="hideUnorderedList">
<li>Second thing to do</li>
<li>Second other thing to do</li>
</ul>
</li>
</ul>
</div>

// Make your code clean and readable!
// Don't target #test. Go directly for your "title/heading" elements ("buttons")
$(".Collapsable").on("click", function() {
// Who is my +/- icon element?
var $ico = $(this).find(".symbol");
// Traverse up to LI and than back down to find my UL sub list:
var $subList = $(this).closest("li").find("> ul");
// Realize the current collapsed/expanded state
var isSubListHidden = $subList.is(":hidden");
// OK, time to rock!
// Change teh text +/-
$ico.text(isSubListHidden ? "-" : "+");
// Toggle sub lists:
$subList.stop().slideToggle();
});
.hideUnorderedList {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<ul id="test">
<li id="first">
<span class="Collapsable"><span class="symbol">+</span>First One</span>
<ul id="myfirstlist" class="hideUnorderedList">
<li>Something to do</li>
<li>Something else to do</li>
</ul>
</li>
<li id="second">
<span class="Collapsable"><span class="symbol">+</span>Second One</span>
<ul id="mysecondlist" class="hideUnorderedList">
<li>Second thing to do</li>
<li>Second other thing to do</li>
</ul>
</li>
</ul>
</div>

Related

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>

How to prepend HTML `<li>` to `<ul>` using jQuery?

I need to append an <li> element to multiple <ul> using a for-loop in jQuery.
Code Snippet:
JQuery:
var lists = $('ul.menu');
for(var i=0; i<lists.length; i++){
var lnk = "<li>All</li>";
lnk = $('<div />').html(lnk).text();
lists[i].prepend(lnk);
}
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menu">
<li>Graphics</li>
<li>Videos</li>
<li>Programming</li>
</ul>
<hr>
<ul class="menu">
<li>Our Story</li>
<li>About Us</li>
</ul>
As per code <li> inserts as the proper text, but is been formatted as plain text instead of an <li>.
What am I doing wrong? How to correct my mistakes?
You're calling the raw DOM prepend (which only exists on modern browsers), because lists[i] accesses the raw ul element. You're also just taking the text of what you want to prepend, rather than including any li markup. You probably want to:
Call jQuery's prepend, and
Include the li in what you're prepending
Example:
var lists = $('ul.menu');
for(var i=0; i<lists.length; i++){
var lnk = "<li>All</li>";
lists.eq(i).prepend(lnk);
}
/* No CSS */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menu">
<li>Graphics</li>
<li>Videos</li>
<li>Programming</li>
</ul>
<hr>
<ul class="menu">
<li>Our Story</li>
<li>About Us</li>
</ul>
A slightly more jQuery-ish alternative to TJ Crowder's solution...
$('ul.menu').each(function() {
$(this).prepend("<li>All</li>");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menu">
<li>Graphics</li>
<li>Videos</li>
<li>Programming</li>
</ul>
<hr>
<ul class="menu">
<li>Our Story</li>
<li>About Us</li>
</ul>

Getting/changing class of an element with other elements in it. JavaScript/JQuery

I made a blog archive in the format of this:
+Year
+Month
Title
Sample code:
<ul>
<span class="toggle">+</span>
<li class="year">$year
<ul>
<span class="toggle">+</span>
<li class="month active">$month
<ul>
<li class="title active">$title</li>
</ul>
</li>
</ul>
</li>
</ul>
I used $(this).next().toggle(), which works fine toggling the lists, but the entire list is expanded in the beginning when the page loads, and I don't want that.
So I changed to changing class names (active/inactive). I want to change the class of the month/title lists to inactive and back when the + span is clicked. The problem is using $(this).next() doesn't work.
If I try $(this).next().hasClass("active");
It will return a false. Or console.log($(this).next().attr("class"));, which gives undefined.
$(this).next().html(); gives:
<li class="month active"><span class="toggle">+</span><ul><li class="title active">...</li></ul></li></ul></li></ul>
The very next thing that follows the + span is the list with class of active, but it doesn't recognize the class? I don't understand why .toggle() works, but this doesn't.
What option do I have to make this work?
The idea is to capture the click event on the span class and toggle active/inactive on the year so that it shows correctly. Here's some psuedo code:
$('.toggle').on('click', function(){
$(this).next().toggleClass('active').toggleClass('inactive');
});
This will only work if the element has a class of inactive on page load, like this:
<ul>
<span class="toggle">+</span>
<li class="year inactive">$year
<ul>
<span class="toggle">+</span>
<li class="month active">$month
<ul>
<li class="title active">$title</li>
</ul>
</li>
</ul>
</li>
</ul>
When you had your initial toggle working but it displayed the items on load, you could have set the next element (the unordered list) to
style="display: none"
As for
console.log($(this).next().attr("class");
You are missing a parenthesis:
console.log( $(this).next().attr("class") );
Hope this helps.
By using little bit of CSS and toggling the class of ul to active only on click will fix your issue. Below is a working example.
$('.toggle').on('click', function() {
$(this).parent().toggleClass('active');
});
ul {
list-style-type: none;
}
ul:not(#MainNode) {
display: none;
}
ul.active > li > ul {
display: block !important;
}
.toggle {
cursor: pointer
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="MainNode">
<span class="toggle">+</span>
<li class="year">Year
<ul>
<span class="toggle">+</span>
<li class="month active">Month
<ul>
<li class="title active">Title</li>
</ul>
</li>
</ul>
</li>
</ul>

javascript horizontal menu click to open

Trying to make javascript horizontal menu, but can't get second button to open its own items, (when i click the second button it opens the items that are for the first button) here is current code:
JavaScript:
$(document).ready(function() {
$(".menu-button,.menu-button1").click(function() {
$(".menu-bar").toggleClass("open");
});
})
HTML:
<ul class="menu">
<li title="home">menu</li>
<li title="pencil">pencil</li>
<li title="about">about</li>
</ul>
<ul class="menu-bar">
<li>Menu0</li>
<li>Home2000</li>
<li>About</li>
<li>Parent</li>
<li>About</li>
</ul>
<ul class="menu-bar">
<li>Menu1</li>
<li>About</li>
</ul>
Before I start my answer, let me explain jQuery a bit.
$(".menu-button,.menu-button1").click(function() {
$(".menu-bar").toggleClass("open");
});
This broken down:
$(".menu-button,.menu-button1").click(function() { -> When any item with class menu-button OR class menu-button1 is clicked
$(".menu-bar").toggleClass("open"); ->Toggle the "open" class for all elements in your page with class menu-bar.
Since you call all the menus instead of the specific one you want, it opens both of them.
So, be more specific by - for starters - using IDs, or unique/identifying classes:
JS:
$(document).ready(function() {
$(".menu-button.home").click(function() {
$(".menu-bar.home").toggleClass("open");
});
$(".menu-button.pencil").click(function() {
$(".menu-bar.pencil").toggleClass("open");
});
})
HTML:
<ul class="menu">
<li title="home">menu</li>
<li title="pencil">pencil</li>
<li title="about">about</li>
</ul>
<ul class="menu-bar home">
<li>Menu0</li>
<li>Home2000</li>
<li>About</li>
<li>Parent</li>
<li>About</li>
</ul>
<ul class="menu-bar pencil">
<li>Menu1</li>
<li>About</li>
</ul>
I agree with M.Doye's comment about using .each (but sorry, I can't answer directly).
I want to add that, it will be much easier with that kind of HTML structure I think:
<ul class="menu">
<li title="home">
Show Menu 1
<ul class="menu-bar">
<li>Menu1
</li>
</ul>
</li>
<li title="pencil">
Show Menu 2
<ul class="menu-bar">
<li>Menu2
</li>
</ul>
</li>
</ul>
The, click on the link and use .next() or .siblings or closest... to show the right ul.
But of course you'll have to rewrite you CSS :)
Here is updated code
$(document).ready(function () {
$(".menu-button,.menu-button1").click(function () {
$(this).siblings(".menu-bar").toggleClass("open");
})
})
<ul class="menu">
<li title="home">menu
<ul class="menu-bar">
<li>Menu1</li>
<li>About</li>
</ul>
</li>
<li title="pencil">pencil
<ul class="menu-bar">
<li>Menu0</li>
<li>Home2000</li>
<li>About</li>
<li>Parent</li>
<li>About</li>
</ul>
</li>
</ul>
here is a jsfiddle

.click() functionality when clicking elements

Basically i want to click on a tab and a drop down menu appears then when you re-click the same tab or any of the others I want it to hide that tab/show the other tab if clicked on the same/other tab.
I tried
$('.click').click(function() {
$(this).find('.sub-nav-list').toggleClass('active');
});
and tried
$('.click').click(function() {
$('.sub-nav-list').removeClass('active');
$(this).find('.sub-nav-list').toggleClass('active');
});
but cant work it out! any insight? Thanks
html:
<nav class="secondary-nav">
<ul class="list clearfix">
<li class="leaders click">Leadership <span class="arrow">></span>
<ul class="sub-nav-list">
<li>Management</li>
<li>Board of Directors</li>
</ul>
</li>
<li class="contact click">Contact Info <span class="arrow">></span>
<ul class="sub-nav-list">
<li>Email Notification</li>
<li>Information Request</li>
</ul>
</li>
<li class="docs click">Documents <span class="arrow">></span>
<ul class="sub-nav-list">
<li>Governance Documents</li>
<li>Press Release</li>
<li>Reports & Presentations</li>
<li>Sec Filings</li>
<li>Frenquently Asked Questions</li>
<li>Tax Information</li>
</ul>
</li>
<li class="research click">Research <span class="arrow">></span>
<ul class="sub-nav-list">
<li>Dividends and Distributions</li>
<li>Stock Information</li>
<li>Analyst Coverage</li>
<li>Market Makers</li>
</ul>
</li>
</ul>
</nav>
I can see at least two possible issues there.
1) sub-nav-list is not a children of click element. If they are on the same level something like that might work:
$('.click').click(function() {
$(this).parent().find('.sub-nav-list').toggleClass('active');
});
2) You have these elements generated dynamically - so you need use on with selector of any parent element that exists before you dynamically generate your sub-menus (let say nav-list):
$(".click").on("click", ".nav-list", function() {
$(this).parent().find('.sub-nav-list').toggleClass('active');
});

Categories