jQuery selecting top level element text - javascript

I have a menu that has the section Store this has a submenu of categories Printers Keyboards and under these categories they have their own sub categories.
What I am trying to do is select the top level categories that are Printers Keyboards just using jQuery into an Array.
When I use the following it prints out ["Printers", "Color", "Black/White", "Dual", "Keyboards", "Wired", "Wireless", "Touchscreen"] This is more than I need for now, could someone help me
Check out my jsFiddle
jQuery
var optionTexts = [];
$('.main-menu ul li a:contains("Store")').parent().find('.sub-menu > li a').each(function(){
optionTexts.push($(this).text());
});
console.log(optionTexts);

EDIT I looked at your fiddle a bit more closeley and changed the way the right "a" tag is found:
'.sub-menu > li > ul > li > a' will do it (I checked it in your jsfiddle):
$('.main-menu ul li a:contains("Store")').parent().find('.sub-menu > li > ul > li > a').each(function(){
optionTexts.push($(this).text());
});
The way you did it, every a underneath the "ul.sub-menu" is selected - also those that are nested in children and grandchildren of "ul.sub-menu".

Hope you are looking for something like this
var optionTexts = [];
$('.main-menu ul li a:contains("Store")').parent().find('.sub-menu').parent('li').each(function(){
optionTexts.push($(this).children('a').text());
});
console.log(optionTexts);

I Edit your code like this, its worked :
$(function () {
$(".check").on('click', function () {
var optionTexts = [];
$('.list > ul > li > a').each(function () {
optionTexts.push($(this).text());
});
c(optionTexts);
});
});
output : Printers, Keyboards
Check it FIDDLE : http://jsfiddle.net/mehmetakifalp/Mkv9q/16/

Related

casperJS contentDocument selector hiddin in #document

I am having trouble clicking a selector in casperJS. If I am not mistaken the selector is hidden in a shadow-root.
this.waitForSelector('#tab > ul > li:nth-child(1) > a',function(){
//yields nothing - timeout
});
this.waitForSelector('#tab > ul > li:nth-child(1) > a',x[0].contentDocument,function(){
console.log("found"); //true
});
where var x is var x = this.evaluate(function(){
var selected = $('frameset>frame');
return selected;
});
When I try and click that. this.click('#tab > ul > li:nth-child(1) > a',x[0].contentDocument);nothing happens.
any help would be greatly appreciate it. thanks a lot!

Hide div if the ul is empty

Here is my html,
<div id="personaldetails">
<ul>
<li class="clear"></li>
</ul>
<ul>
<li class="clear"></li>
</ul>
</div>
I want to hide div personaldetails when all the ul inside in div is empty.
If the ul is having element <li class="clear"></li> then the ul is considered as to be empty.
How to do this using Jquery ?
You can try this:
$('#personaldetails').find('ul').each(function(){
var txt = $("li", this).text();
if(txt.length <= 0){
$(this).hide();
}
});
if(!$('#personaldetails').find('ul:visible').length){
$('#personaldetails').hide();
}
Updated Fiddle
And to me you should hide all ul, if no ul are visible then you can hide the #personaldetails div.
Even one of answer is already accepted, I think it can be simple as:
if($.trim($("#personaldetails").text()) == '') {
$("#personaldetails").hide();
}
:)
Take a look at that code:
function foo(){
var all_li_clear = true;
$("#personaldetails > ul > li").each(function(){
if(!$(this).hasClass("clear")){
all_li_clear = false;
break; // No need to continue now
}
});
if(all_li_clear){
$("#personaldetails").hide();
}
}
You can see a fiddle example there, just comment and discomment foo(); line.
Javascript solution:
This will only hide the div if all li have clear class
$(function() {
emptyLi = $('#personaldetails ul li').filter(function(){
/*if($(this).hasClass('clear')){
return true;
}else{
return false;
}*/
return $(this).hasClass('clear');
}).length;
if($('#personaldetails ul li').length == emptyLi){
$('#personaldetails').css('display','none');
}
});
CSS:
This will hide the li with class clear, so if you not fixed height of ul or li and don't have padding , margin given to ul,li your div personaldetails will get hidden automatically when all li element have class clear
#personaldetails ul li.clear{
display:none;
}
-UPDATED-
You can use following code if you are deciding empty class based on clear class.
if($("#personaldetails ul li:not(.clear)").length == 0) {
$("#personaldetails").hide();
}
Or if you are looking for the empty div then you can just use the shortest code given by #Samiul Amin Shanto Like:
if($.trim($("#personaldetails").text()) == '') {
$("#personaldetails").hide();
}
Explanations
Method1:
$("#personaldetails ul li:not(.clear)")
This code find all li without the clear class. Then if no such li found, just hide the div. Fiddle
Method2:
$("#personaldetails").text() this code return innerHTML text striping all html tags. So no meter what the div contain ul, li or anything else, this will return the plain text content of the div, then striping any white space we can determine if the div is empty. If your intention is to hide the empty div not hiding the div which contain empty Ul this should be your choice.
This asumes that if you have the same amount of li's with the class clear, as there are ul's, they're all empty
var $wrapper = $('#personaldetails');
if( $wrapper.find('ul').length=== $wrapper.find('li.clear').length){
$wrapper .hide();
}
Everybody's fiddling examples :)
$(function($) {
$cnt = 0;
$('.personalDetails ul li').each(function() {
if($(this).hasClass('clear')) $cnt++;
});
if($('.personalDetails ul li').length == $cnt) $('.personalDetails').hide();
});
$("ul li:empty").closest('div#personaldetails').hide();
Sample Code
#personaldetails ul li.clear{
visibility:hidden;
}

Issue with adding UL markup for LI

This sounds simple, and it should be, but it doesn't seem to be so cut and dry...
I have a list of li elements..
<li>Text here</li>
<li>Text here</li>
<li>Text here</li>
What I want to do is find the 1st one, add <ul> before it. Find the last one, add </ul>
It sounds simple but stay with me...
First I tried this:
$('li').each(function(i,obj) {
var x = $(this);
if(x.prev().prop('tagName')!=='LI') x.before('<ul>')
if(x.next().prop('tagName')!=='LI') x.after('</ul>')
});
Which evolved into this:
$('li').each(function(i,obj) {
var x = $(this);
$.fn.outerHTML = function(){
var x = $(this);
x.wrap('<p/>')
var html = x.parent().html();
x.unwrap();
return(html);
}
alert(x.outerHTML());
if(x.prev().prop('tagName')!=='LI') x.html('<ul>'+x.outerHTML())
if(x.next().prop('tagName')!=='LI') x.html(x.outerHTML()+'</ul>')
});
The 1st code places an empty UL before the 1st LI (closing tag and all)
The 2nd wraps only the 1st LI.
It goes down the list 1, 2, 3 and seems to report back properly... something (possibly jQuery) seems to be altering my code somewhere along the way. Can anyone shed some insight here?
Fiddle to fiddle with: http://jsfiddle.net/yr67N/
Update:
As you can see from the code, the lis must be grouped together. wrapAll won't work here.
Just tried this on your fiddle and it appears to work:
var collectedLi = [];
$('li').each(function(){
collectedLi.push(this);
if(!$(this).next().is('li')){
$(collectedLi).wrapAll('<ul/>');
collectedLi = []
}
});
For every li it will check if the next element is also an li, if not it will wrap the current collection in a ul and then empty the collection to continue the loop.
Just realized that the above code will also wrap already wrapped li tags, here is a solution that will handle this:
var collectedLi = [];
$('li').each(function(){
collectedLi.push(this);
if(!$(this).next().is('li')){
if(!$(this).parent().is('ul')){
$(collectedLi).wrapAll('<ul/>');
}
collectedLi = []
}
});
How about:
$('li').wrapAll('<ul/>');
Fiddle
var ul,
tname;
$('li').each(function(i, el){
tname = $(el).prev().prop('tagName');
if(String(tname) !== 'UL'){
ul = $('<ul></ul>');
$(el).before(ul[0]);
}
$(this).appendTo(ul);
});
fiddle

How to count width of same type elements till some element

HTML:
<li class="home"><img alt="home" src="img/gohome.png"/></li>
<li class="portfolio closed" ><span>portfolio</span></li>
<li class="articles opened" style="margin-right: 849px;"><span>articles</span></li>
<li class="contact"><span>contact</span></li>
JS:
$('nav li').each(function(index) { //Navigation total width
navWidth += $(this).width();
});
I have script like that which works, but I also have to count width of Li elements till some specific element basing on class for ex. portfolio. And i don't have idea how to do it.
Another option with nextUntil():
$("nav li:first").nextUntil(".portfolio").andSelf().each(function(index) {
navWidth += $(this).width();
});
One way could be to exit the loop when you encounter an element with that class:
$('nav li').each(function() {
if ($(this).hasClass('portfolio')) {
return false;
}
navWidth += $(this).width();
});
Another way is to just select all the elements until the element with class portfolio. This can be done by getting the index of said element and select all elements up to that index:
var $lis = $('nav li');
$lis.slice(0, $lis.filter('.portfolio').index()).each(function() {
// ...
});
This is under the assumption that all those li elements are siblings of each other.
Reference: .each, .filter, .slice

make parent menu item bold when visiting child page

I have the following code which gives the menu item a class of 'current'. I then style that with font-weight:Bold;
$(document).ready(function () {
var loc = window.location.href;
$("ul a").each(function() {
if (loc.indexOf($(this).attr("href")) != -1) {
$(this).addClass("current");
}
});
});
If the user is on a page which is within the sub menu ul li a how do i add a class called Bold to the parent UL/LI at the root level?
here is the structure, if i am on Q&Z Group then About us needs to be bold. - http://jsfiddle.net/zZQy3/
var loc = window.location.href;
$("ul a").each(function() {
if (loc.indexOf($(this).attr("href")) != -1) {
$(this).addClass("current");
$(this).parent('li').parent('ul').addClass("Bold");
}
});
You are looking for the parent:
$(this).parent("li").parent("li").addClass("bold");
Note there are two parents above - this is because your a element is within an li, which is not what you want bold. You want the li parent of THAT to be bold.
if you have the current node as a jquery variable, you can access its parent by using parent. So, you could use $(this).parent().addClass(...);
If you wanted to, rather than using javascript for this logic, you could use the selector:
$('ul li:has(a[href=' + window.location.href + '])').addclass(...);
This is looking for any LI that has a descendant with an href matching the current url by way of the Has and Attribute Equals selectors.

Categories

Resources