Jquery get number of nested elements - javascript

Consider a dynamic dropdown-menu. Because of creating this code server side I don't know the exact number of li situated in div 'sub'.Example HTML output:
<li>
Videos
<div id="sub">
<ul>
<li>Main</li>
<li>Acting</li>
<li>Animals</li>
</ul>
</div>
</li>
The following script should give the number of li in the in div id="sub"
$(function() {
$('.tabMenu li a').click(function() {
currentLink = $(this);
//Get number of children elements
alert(currentLink.children().size());
});
Any help will be greatly appreciated.

alert(currentLink.parent().find('li').size());

First: where is your .tabMenu in your code?
Try with:
.length;
Working solution
$('.tabMenu li a').click(function() {
currentLink = $(this);
alert(currentLink.parents('ul').children('li').length);
});

What you need to do is get the parent container of the li element, then see how many children it has:
$(function() {
$('.tabMenu li a').click(function() {
// Get the parent ul of the current link
var currentLinkParent = $(this).parents("ul:first");
alert(currentLinkParent.children().size() );
});

Related

How to access list items within ul that get added via a jquery function

I am basically working on a responsive navigation bar where if the current window width doesn't accommodate the number of items, last item of the list will get appended to another un-ordered list.
My problem is I need to target menu items within the hidden list which is empty when the width of the window is 100%. I could access the un-ordered list for visible list but not for the hidden list as per below jQuery. I understand that I am trying to access items that doesn't exist yet, but there must be a way.
Snippet:
var $vlinks = $('#hrmenu .visible-links');
var $hlinks = $('#hrmenu .hidden-links');
availableSpace = $vlinks.width() - 30;
var
break = [];
areaAvail += w + 20;
break.push(areaAvail);
visibleItems = $vlinks.children().length;
requiredSpace =
break [visibleItems - 1];
if (requiredSpace > availableSpace) {
$vlinks.children().last().prependTo($hlinks);
}
$(document).ready(function() {
//Visible list
$('#shuffle-btn > li > a').click(function(event) {
$item = $(event.currentTarget).parent('li');
console.log($item.index());
});
//Hidden list list
$('#hidshuffle-btn > li > a').click(function(event) {
$item = $(event.currentTarget).parent('li');
console.log($item.index());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav id="hrmenu" class="prdct-hrmenu">
<ul id="shuffle-btn" class="visible-links">
<li>item-1
<ul>
<li>Item-1-a</li>
</ul>
</li>
<li>item-2
<ul>
<li>Item-1-a</li>
</ul>
</li>
<li>item-3
<ul>
<li>Item-3-a</li>
</ul>
</li>
<li>item-4
<ul>
<li>Item-4-a</li>
</ul>
</li>
</ul>
<ul id="hidshuffle-btn" class="hidden-links">
</ul>
</nav>
As the elements in the hidden list are not available during DOM ready, you need to define a click handler that can delegate to these elements when they are available. You can use JQuery's on function for this like below.
$(document).ready(function(){
//Hidden list list
$('#hidshuffle-btn').on('click', ' li > a', function(event){
var $item = $(event.currentTarget).parent('li');
console.log($item.index());
});
});
Here's a sample Pen in action :)
For dynamically added elements, you just need to change your line from:
$('#shuffle-btn > li > a').click(function(event) {
to
$(document).on('click', '#shuffle-btn > li > a', function(event) {
Similarly for the hidden list:
$('#hidshuffle-btn > li > a').click(function(event) {
to
$(document).on('click', '#hidshuffle-btn > li > a', function(event) {
**#Arkantos's answer is more correct in terms of performance.

Find if current class contains word, then append new class to those li's - jquery

Having some problems with jQuery methods - perhaps overcomplicating things...
What I need to find is if any of the li elements classes contain the word 'current', then if they do, append the word active to them.
I'm struggling to add the word to the end of the current class. For example:
Markup:
<div class="menu-navigation-container">
<ul>
<li class="current_page_item menu-item-8787"><span>The Magazine</span>
</li>
<li class="menu-item menu-item-type-post_type"><span>Snapped</span>
</li>
</ul>
</div>
jQuery:
$(document).ready(function () {
var classNames = $('.menu-navigation-container ul li').attr("class").match(/[\w-]*current[\w-]*/g);
$(classNames).each(function () {
$(this).addClass("active");
});
});
Running classnames; up in the console produces just the string - I want it to reference the li elemens that have the word 'current' in their class names, then append the word 'active' at the end.
Can I do this with jQuery's attribute contains selector?
Simply like this :
$(document).ready(function () {
$('.menu-navigation-container ul li[class*=current]').addClass('active');
});
Try this
$(document).ready(function () {
$('.menu-navigation-container ul li').each(function(){
if ( $(this).is(".current") )
{
$(this).addClass("active");
}
})
});

nth-child increase decrease with click

I have a set of li elements forming a menu. When the user clicks a particular li element I want to change the source of an iframe element to the URL that corresponds to the clicked item.
I've tried the function below but it didn't work. Can somebody please advise how to do this?
http://jsfiddle.net/ZnMTK/8/
$(document).ready(function(){
var source1="http://www.hurriyet.com.tr";
var source2="http://www.milliyet.com.tr";
var source3="http://www.vatan.com.tr";
var source4="http://www.ensonhaber.com";
$("#menubar ul li:nth-child(i)").click(function(){
$(this).attr('src', source(i) );
});
});
You can use an array and then use the clicked li elements index to fetch the target source from array.
$(document).ready(function(){
var sources =["http://www.hurriyet.com.tr","http://www.milliyet.com.tr","http://www.vatan.com.tr","http://www.ensonhaber.com"],
$("#menubar li").click(function(){
$('#iframe1').attr('src', sources[$(this).index()])
});
});
Demo: Fiddle
This type of functionality is what arrays are for:
$(document).ready(function(){
var sources =["http://www.hurriyet.com.tr","http://www.milliyet.com.tr","http://www.vatan.com.tr","http://www.ensonhaber.com"],
i = 0;
$("#menubar li").click(function(){
$("#iframe1").attr('src', sources[$(this).index()] );
});
});
However, specifying all of your URLs in your JavaScript and relying on the indices matching up with the order of the menu li elements is kind of fragile. I would recommend linking the values more closely, perhaps something like this:
<ul id="menubar">
<li data-src="http://www.hurriyet.com.tr">Hurriyet</li>
<li data-src="http://www.milliyet.com.tr">Milliyet</li>
<li data-src="http://www.vatan.com.tr">Vatan</li>
<li data-src="http://www.ensonhaber.com">Ensonhaber</li>
</ul>
And then with JS:
$(document).ready(function () {
$("#menubar li").click(function () {
$("#iframe1").attr('src', $(this).attr("data-src"));
});
});

Jquery add selected class to li

Hi i have following ul li that display categories name:
<ul>
<li class="selected" data-tab-id="0"></li>
<li data-tab-id="12">...</li>
<li data-tab-id="3">...</li>
<li data-tab-id="15">...</li>
<li data-tab-id="7">...</li>
</ul>
The javascript scripts as follow:
<script type="text/javascript">
var cat_id = '<?=$this->catid?>'
$(document).ready(function () {
});
</script>
Currently the page at index so first li data-tab-id="0" will be selected class also var cat_id will be return nothing. Now when user navigate to another tab such as data-tab-id="12", var cat_id will be return value of 12, how can i remove class selected from default li and replace it to data-tab-id="12". Thanks
Assuming list as ID of the UL – just to avoid problem in case you have multiple UL around the page:
$("ul#list")
.find(".selected").removeClass("selected")
.end()
.find("[data-tab-id=" + cat_id + "]").addClass("selected");
You can also do that in two jQuery calls, of course:
$("ul#list .selected").removeClass("selected");
$("ul#list [data-tab-id=" + cat_id + "]").addClass("selected");
use addClass() and removeClass() to add and remove class respectively.
try this
updated
var cat_id = '<?=$this->catid?>';
$('li').removeClass('selected');
$('li').each(function(){
if($(this).attr('data-tab-id')==cat_id){
$(this).addClass('selected');
}
})
updated without using loop..
var cat_id = '<?=$this->catid?>';
$('li').removeClass('selected');
$('li[data-tab-id='+cat_id+']').addClass('selected');
fiddle here
updated fiddle
use this sample
$('ul li').click(function() {
$('ul li.selected').removeClass('selected');
$(this).closest('li').addClass('selected');
})

Need clean jQuery to change parent's class when children are clicked

I needed some method of adding/removing classes of a parent element when it's children are clicked to reflect which child is currently selected. In this case a UL parent and LI children in a tab scheme. I needed a way to mark the current tab on the UL so I could style a background sprite on the UL; since styling my LI's backgrounds would not work with the graphics in this case.
I am a jQuery/Javascript/DOM novice, but was able to piece together an ugly solution for starters,
HTML
<!-- tabs -->
<ul class="tabs currenttab-info">
<li id="tab-info" class="info"><strong>Information</strong></li>
<li id="tab-write" class="write"><strong>Write Feedback</strong></li>
<li id="tab-read" class="read"><strong>Read Feedback</strong></li>
</ul>
Javascript
// send '.currenttab-x' to '.tabs' and remove '.currenttab-y' + '.currenttab-z'
// when LI #tab-X is clicked ...
$( '#tab-info' ).click(function() {
// ... find the UL and remove the first possible conflicting class
$('.tabs').removeClass("currenttab-read");
// ... find the UL and remove the other possible conflicting class
$('.tabs').removeClass("currenttab-write");
// ... find the UL and add the class for this LI
$('.tabs').addClass("currenttab-info");
});
// ... repeat ...
$( '#tab-write' ).click(function() {
$('.tabs').removeClass("currenttab-info");
$('.tabs').removeClass("currenttab-read");
$('.tabs').addClass("currenttab-write");
});
$( '#tab-read' ).click(function() {
$('.tabs').removeClass("currenttab-info");
$('.tabs').removeClass("currenttab-write");
$('.tabs').addClass("currenttab-read");
});
This actually seems to be working, BUT it's a fumbling solution and I am sure there is a better way. Some of you jQuery ninjas will know how to put this functionality together really elegantly, any help?
Also I would like to add onto this so that the clicked LI is also given a class to show it is selected while the other LIs are stripped of any such class. The same sort of thing I already am doing for the UL; I can see how to do that with my awkward approach, but it will mean even more and more lines of messy code. If your improvement also included a way to do change classes of the LIs I'd appreciate it
FYI: I'm using jQuery Tools Tabs with this so there is more jQuery then I showed, but only the bit I quoted seems relevant.
html
I will remove ids of li if you are not using it for other purposes.
<ul class="tabs currenttab-info">
<li class="info"><strong>Information</strong></li>
<li class="write"><strong>Write Feedback</strong></li>
<li class="read"><strong>Read Feedback</strong></li>
</ul>
jQuery
$('.tabs li').click(function() {
var $li = $(this);
$li.addClass('current').siblings().removeClass('current'); // adds a current class to the clicked li
var $ul = $li.parent();
$ul.removeClass("currenttab-info currenttab-read currenttab-write")
.addClass("currenttab-" + this.class ); // assuming li only holds one class e.g. class="write"
});
You can just do something like this:
$('.tabs > li').click(function() {
$(this).parent().attr('class', 'tabs').addClass('currenttab-'+$(this).attr('class'));
});
$("UL.tabs LI A").bind('click',function(e){ //bind a Click-Event handler to the Links
var $target = $(e.target); //the jQuery-Object-Reference to the clicked target ( $(this) should work too)
var LIClasses = $target.parents('LI').attr('class'); //A list of all Classes the parrent LI of the clicked Link have
$target
.parents('UL.tabs')
//now you can remove and add classes to the parent "UL.tabs"
.removeClass('...')
.addClass('...')
.end() //after .end() the chain for .parents-match is broken
.parents('LI')
//here you can add and remove classes from the parent LI
.removeClass('...')
.addClass('...')
.end() //after .end() the chain for .parents-match is broken
;
});
Notes:
jQuery is chainable.
.removeClass() and .addClass() can work with multiple classnames at the same time by speration with a space (like .removeClass('class1 class2'))
The full solution:
var relevantClasses = ['read','write','info'];
$("UL.tabs LI A").bind('click',function(e){
var $target = $(e.target);
var relevantClass = '';
for( var cl in $target.parents('LI').attr('class').split(' ') )
if( jQuery.inArray(relevantClasses , cl) > -1 ){
relevantClass = cl;
break;
}
$target
.parents('UL.tabs')
.removeClass(jQuery.map(relevantClasses , function (className) { return 'currenttab-' + className; }).join(' '))
.addClass('currenttab-'+relevantClass )
.end()
;
});
First of all you can chain the method calls...
$('.tabs').removeClass("currenttab-read currenttab-write").addClass("currenttab-write");
This would make the code much cleaner...
EDIT: I'll try such things in Fiddle http://jsfiddle.net/JvtAz/

Categories

Resources