Jquery child selector vs. .each - javascript

Given the following example table:
<ul class="topnav">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
What are the differences between:
$selector1 = $('ul.topnav > li');
and
$selector2 = $('ul.topnav').each();
EDIT:
$selector2 = $('ul.topnav li').each();

The first will contain all li's which are a direct child of ul.topnav, the second will contain all ul.topnav elements.

$('ul.topnav > li') will select all <li>s directly under the ul.
each should take a function as a parameter, and iterate over all matched <ul> - it doesn't not take the children <li>s. If anything, you want $('ul.topnav').children(), which is identical if the ul only contains li elements anyway.
For example, this will alert the number of children each list has (in your case, only the number 3)
$selector2 = $('ul.topnav').each(function(){
alert($(this).children().length);
});
Also see the jquery API.

The second one will evaluate them individually, whereas the first one will evaluate them as a group

Related

jQuery get list item value

I have a basic html list
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li class="active">Item 3</li>
<li>Item 4</li>
</ul>
I am trying to get the value of list item which has class of active. So, I can find the item by using...
$("ul li.active");
But .val() is not working on list items. What should I be using instead?
The .val() method is primarily used to get the values of form elements such as input, select and textarea.
You should use .text() to get text of li element.
$("ul li.active").text()
Use .text() instead of .val()
.val() works on input elements (or any element with a value
attribute?) and .text() is for the innerHTML (similar to .html() ).
you can look at following jsbin.
JSBIN
Use .data().value instead of .val() when working with li element.
<li data-value="20">twenty</li>

Ordered List Iteration in Javascript

Is there a way to allow me to iterate through an ordered list similar in functionality as table.rows? I am using Javascript.
The reason I ask this is because I have an ordered list that contains another ordered list inside. I just want to return the parent list items and not the child.
<ol id="pList">
<li>Item A</li>
<li>
<ol id="cList">
<li>A's Child 1</li>
<li>A's Child 2</li>
</ol>
</li>
<li>Item B</li>
<li>Item C</li>
<li>Item D</li>
</ol>
I now use getElementsbyTag and that returns all li's including the one in cList. I just want the ones in pList.
Thanks
FYI: I would prefer it done in Javascript. The code has to work within Greasemonkey. I don't really know much about jquery and I am not really much of a javascript programmer.
There is no specific property that gives you direct access to the <li> children of an <ol>.
However it is very easy to enumerate them, particularly when you consider that the only legal children of an <ol> must be white space text nodes and <li> nodes.
var ol = document.getElementById('pList');
var li = [];
var node = ol.firstChild;
while (node) {
if (node.tagType === 3 && node.tagName === 'LI') {
li.push(node);
}
node = node.nextSibling;
}
At the end of which, the array li contains the required children.
The above code will work in any browser. The .children collection has problems on older versions of MSIE, and querySelectorAll is even more modern (and therefore less widely supported).
If using querySelectorAll()* is an option for you, it's easy:
var listItems = document.querySelectorAll( '#pList > li' );
* note: it's a native DOM method, and has nothing to do with jQuery
There's a table of immediate children in every javascript object :
document.getElementById('pList').children
You can even iterate through it and check whatever your need :
var el = document.getElementById('pList');
for (var i = 0; i < el.children.length; i++) {
if (el.children[i].tagName == "LI") {
el.children[i].doWhatever();
}
}

Add different classes to list item parents using jquery

I have a list with different levels of depth:
<ul>
<li>Item 1</li>
<li>Item 2
<ul class="sub-menu">
<li>Sub item 1</li>
<li>Sub item 2</li>
<li>Sub item 3
<ul class="sub-menu">
<li>Subsub item 1</li>
<li>Subsub item 2</li>
</ul>
</li>
<li>Sub item 4</li>
</ul>
</li>
<li>Item 3</li>
</ul>
I am using the following jquery script to add a class to the parents:
$("ul li ul").parent().addClass("menuparent");
Is there a way to add this class only to the top level parent li's and a different class for all other (deeper) parent li's?
Here is one way to do it.
$("ul li ul").parent().addClass("otherclass");
$("ul li >ul").parent().removeClass("otherclass").addClass("menuparent");
​
http://jsfiddle.net/MdBa5/
You could run a closest check to see if there are any parents that are li.
if ($element.closest("li").length === 0) {
$element.addClass("topLvl");
} else {
$element.addClass("innerLvl");
}
Try:
$("ul:first>li").addClass("menuparent")
.find('li>ul').parent().addClass('otherparent');
http://jsfiddle.net/3UcdM/
Here's a recursive solution:
function markNestedLists(par, level){
par.addClass("level-" + level);
par.children("li").children("ul").each(function(){
markNestedLists($(this), level + 1);
});
}
markNestedLists($("ul").first(), 1);
http://jsfiddle.net/h9xvY/1/
If you know the ID of the parent of the topmost UL you could use it like so:
markNestedLists($("#myParent > ul"), 1);
Depending on what you want the names of the classes to be, I'd use this:
$(function(){
$('ul li').addClass(function(){
return 'depth-' + $(this).parents('ul').length;
});
});​
You can see a working example here: http://jsfiddle.net/russelluresti/3peCS/
If you want special class names, and not number additions, you'd have to run a switch statement. But the concept is the same. Use a function inside addClass to determine the depth (by using parents()) and return the appropriate value.
Ideally, there's some absolute reference like an ID or other searchable attribute that is unique to the top-most ul, but you can work around that. Either way, the important thing is the child selector: > instead of the implicit descendant selector. It will specify that you only want to find ul's that are exactly so many levels below that top-level element.
When, in your base case, you use:
$("ul li ul").parent()
you get all ul's that are any descendant (children, grandchildren, great-grandchildren...) of any li's, that are descendant of any ul's. Instead, you'd use:
$("ul#topmost > li > ul").parent()
which gets you only a ul that is the child of an li that is a child of the specific ul at the top of the tree.
If you don't have an id or other explicit selector for the top of the tree, the top-level ul must itself be a child of either a div or body or some other block-level element. So, you can clearly and distinctly get the hierarchy you want by just adding that parent of the top-level ul:
$("body > ul > li > ul").parent()
Also: I forgot that you also wanted to be able to select the other parent li's that aren't captured by the selector above. You can do that using the :not selector, or JQuery's .not() method, like so:
$("li>ul:not(body > ul > li > ul)").parent()
To combine the two lines into one, you'd first add the deeperParent class to all such li's, then filter for the top-level parent, and assign menuParent only there:
$("li>ul").parent().addClass('deeperParent').filter('body > ul > li').
removeClass('deeperParent').addClass('menuParent')

JQuery Prepending text in front of a link

I have a unordered list with links and sublinks. I'd like to prepend a '»' character in front of the sublinks in the list. I could probably do this with CSS via list-style-image:url but I'd rather just have text. So far I have tried prepend without much success.
HTML:
<nav>
<ul>
<li>link 1</li>
<li>link 2</li>
<ul>
<li>sublink link 1</li>
<li>sublink link 2</li>
</ul>
<li>link 3</li>
</ul>
</nav>
And I am using this code:
$("ul li li").each(function() {
$(this).closest('li').prepend("»").html();
});
If I take away one level of list items and prepend to all list items, then it works but viewing in web inspector, the » character still has quotes around it. I also tried various incarnations of what appeared for closest such as li a but that did not make a difference either. I'm not getting any syntax errors so not sure what I am doing wrong.
I have a Fiddle here.
Why not some css?
ul ul li:before {
content: '»';
}
Using JavaScript to modify the UI for something like this is a waste of resources. This is subjective without knowing your actual use case.
Your selector is not correct, also there is no need to use html and each methods.
$("ul ul li").prepend("»");
You had an incorrect selector ul li li implied there was an li directly within an li but there is another ul between.
In addition you don't need to use a .each for that as jQuery will return the reference to the set of elements which matched the selector.
$("ul ul li").prepend("»");
DEMO
Mind you the CSS solution from Aknosis looks very cool.
I think this is what you are needing:
$("ul ul li").prepend("» ");
Try:
$("ul li").each(function() {
$(this).prepend("»").html();
});

Filter method jQuery

Please help me out with the following code. I don't understand it. I have to use a snippet like this in my project.
$('strong', this) <- this part is not clear to me at all.
Please be kind enough to explain the whole code line by line if possible.
<ul>
<li><strong>list</strong> item 1 -
one strong tag
</li>
<li><strong>list</strong> item <strong>2</strong> -
two <span>strong tags</span>
</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
<li>list item 6</li>
</ul>
JavaScript:
$('li').filter(function(index) {
return $('strong', this).length == 1;
}).css('background-color', 'red');
$('strong', this) is jQuery selector with $(target, context) format.
According to your code:
this refers to li and $('strong', li) is searching a <strong> that within that li tag.
This statement can also be written as:
$(this).find('strong') and from jQuery library code you'll see that:
$(target, context) format internally implement the
$(context).find(target) process.
For more see here.
The code is basically getting a list of li elements using the jQuery $('li') (this will get all <li> ... </li> tags on the page)
It then reduces this set with the .filter function, filter takes a function as an argument, the function is called on each element in the list, if it returns true the element is returned in the list from filter if it return false the item is ignored.
In this context the function calls $('strong', this).length == 1 where this is the li tag that currently being decided checked by the filter, as mentioned in other answers it's simply checking returning the list of <strong>..</strong> tags in the current li. If there is not strong in the current li, length is 0 so the function returns false, this means the filter wont return that element in the list it produces, it then moves on to the next li.
this means the the first part of the code simply produces a list of li's with a strong tag in them, this is then chained with the css function which colours all those tags in red.
Hope that helps.

Categories