How to find index of li which doesn't have id? - javascript

Hi I am creating tabs in JSP using twitter bootstrap.
<ul>
<li id="first">General</li>
<li>Transport</li>
<li>Data Map</li>
<li>Schedule</li>
</ul>
Now I have given id for first LI but dynamically I will be giving id to LI.
How to find the index of LI which does not have id? If the second one has no id, it should find the index of that LI only and should not check for remaining LI How can I get that?

Try with :not .first() and .index():
var idx = $('li:not([id])').first().index();
console.log(idx);
Demo
This will get you the index of first li which doesn't have an id.

You are probably looking for Siblings(). You could also get a reference to the Parent() and go from there.

$('ul li').each(function(index){
$(this).addClass('index-'+index);
});
Example here:
http://jsfiddle.net/superbshivam/HqpSF/

Very quick and dirty approach, but it should get you started on what you need.
var indexWithoutId = -1;
$(document).ready(function() {
findIndexWithoutId();
console.log("without id: " + indexWithoutId);
});
function findIndexWithoutId() {
$("li").each(function() {
var index = $(this).index();
var id = $(this).attr("id");
if (typeof(id) === "undefined") {
indexWithoutId = index;
return false;
}
});
}
Working jsfiddle example

jQuery has a function for this:
$('li').on('click',function(){
alert($(this).index());
});
NB: .index() returns a zero-based index.
Here is a working jsfiddle
To only target li's without an id, make use of the :not() selector and [id] attribute selector:
$('li:not([id])').on('click',function(){
alert($(this).index());
});
Updated jsFiddle
Source(s)
jQuery API - .index()

Related

jQuery: assign array values to another set of elements

I have this code:
jQuery(document).ready(function($) {
var i = 0;
var values = [];
var element = $('.source');
element.each(function(i) {
values[i++] = $(this).text();
});
});
I want to assign each array value above, as the individual data-text value on another set of list elements. Something like this:
<ul id="list">
<li data-text="arrayvalue1"></li>
<li data-text="arrayvalue2"></li>
<li data-text="arrayvalue3"></li>
</ul>
I don't understand how I would do this using jQuery.
You can use attr() to assign data-text values with values from another array. With each() loop you are iterating over all li elements in ul and adding values from element array starting from 0, and you are also incrementing i by 1. So on second li, value of i will be 1 which is arrayvalue2 etc...
var element = ["arrayvalue1", "arrayvalue2", "arrayvalue3"]
var i = 0;
var values = $('ul li').each(function() {
return $(this).attr('data-text', element[i++]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="list">
<li></li>
<li></li>
<li></li>
</ul>
Instead of using jQuery's each(), try using this higher order function.
I don't have a complete picture of how your object looks but something like this should work:
element.forEach((el) => {
el.dataset.text = referencedValue
}
There's no need for the "i" var, just do a push to the array of values. Like this:
jQuery(document).ready(function($) {
var values = [];
var element = $('.source');
element.each(function(i) {
values.push($(this).data('text'));
});
console.log(values);
});
See this fiddle https://jsfiddle.net/masqueradecircus/errq8cp7/3/
Provided you have your source elements you can iterate through them and apply the data attribute referring to the index of the element:
var element = $('.source');
element.each(function(i) {
$('#list > li').eq(i).attr('data-text', $(this).text());
//or
$('#list > li').eq(i).data('text', $(this).text());
});
Note: the difference of the two lines is:
.attr() will apply the value in the dom as an attribute to the element (visible in the html markup). The value can be retrieved with .data() or .attr()
The second one applies the value as an association to the element, which will not be reflected in the dom. This can only be retrieved with .data()
Example
Use $('.source li') and then you can use attr property in jquery to set the data-text attribute in another list.
Please find the sample below:
https://jsfiddle.net/vgade/km113ztL/
jQuery(document).ready(function($) {
var i = 0;
var values = [];
var element = $('.source li');
element.each(function(i) {
$('#destination li')[i].attr("data-text",$(this).text());
i++;
});
});

get text of the first li element from every ul

I have a lot of <ul> list and try to get from every first li of this list the text.
the markup is simple like:
<ul>
<li>abc</li>
<li>def</li>
<li>ghi</li>
</ul>
and so on.
my jQuery attempt is:
var elems = $('ul'); // returns a nodeList
var arr = jQuery.makeArray(elems);
arr.reverse(); // use an Array method on list of dom elements
for( var i=0; i < elems.length; i++) {
console.log($(this).find('li:lt(1)').text());
}
But I have a mistake in the for loop with $(this). I don't know how to get the first text of ul number 1 or 3 if i don't use $(this).
So how can point it correctly in the for loop?
.each will give you this.
$('ul').each(function() {
console.log($(this).find('li').eq(0).text());
})
Alternative sytax using :first instead of :eq(0)
$('ul').each(function() {
console.log($(this).find('li:first').text());
});
or, to forgo the find() function.
$('ul').each(function() {
console.log( $('li:first', this).text() );
});
you can also use:
$("li:nth-child(1)").each(function()
{
console.log($(this).text());
});
notes:
with :nth-child(n), all children are counted, regardless of what they are.
with :nth-child(n), n is 1-based (the first index is 1 instead of 0)

set array content to title of span tag with JQuery

i have an array like this:
var name = ["cat","shark","tiger","snake"];
i want set array content to <span> title.
HTML CODE:
<ul id="select">
<li class="ui-state-default"><span>CAT</span></li>
<li class="ui-state-default"><span>SHARK</span></li>
<li class="ui-state-default"><span>TIGER</span></li>
<li class="ui-state-default"><span>SNAKE</span></li>
</ul>
jquery code:
for(var i=0; i<=name.length; i++){
$('#select li > span').each(function() {
this.title = name[i];
});
};
but this code don't work.
title of span is be undifined.
If by title you mean the text of the span, I'd suggest:
$('#select li span').text(function(i){
return name[i];
});
JS Fiddle demo.
Or if you're trying to set the title attribute, I'd suggest:
$('#select li span').attr('title',function(i){
return name[i];
});
JS Fiddle demo.
It doesn't make sense to loop over the spans and the array. Also the i <= name.length means that you will always loop past the array (should be <). This means that you were actually setting each span's title to an array element that did not exist.
$('#select li > span').each(function(i) {
$(this).attr('title', name[i]);
});
You may also want to check that name[i] exists.
http://jsfiddle.net/wtbE5/
Try:
$('#select li span').each(function(i){
$(this).html(name[i]);
});
Sample

which <li> element was clicked?

I have 5 (maybe more) li elements.
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
I want to get which elements was clicked(which row??). If random user clicks Two I want to get $("li:eq(1)")(as typed).
How can I get this result?
You can use jQuery.index. Something like this:
$('ul > li').click(function() {
alert($(this).index($(this).parent('li'));
});
You can get the text node value of the clicked item with:
$('li').click(function(){
var clicked = $(this).text();
alert(clicked+" was clicked");
});
$("#ulId li").click(function() {
$(this).something(); //the clicked li is $(this), and you can invoke functions on it.
})
If you give your elements an id such as
<ul id="mylist">
<li id="el_1">One</li>
<li id="el_2">Two</li>
<li id="el_3">Three</li>
<li id="el_4">Four</li>
<li id="el_5">Five</li>
</ul>
Then you can use $(this).attr(id) in the click handler to determine the id of the clicked element. This will also allow to give non sequential ids to your elements, and will detach what's written in the <li> from the actual value you get.
Also, you can encode multiple value in the id (for instance el_5_3) which can be useful sometimes.
$("#mylist li").click(function()
{
var id = $(this).attr("id").split("_");
alert("You clicked the element with id="+id[1]);
});
Working example:
http://jsfiddle.net/jFrdp/
Working example: http://jsfiddle.net/tbugV/1/
$("#mylist li").each(function(index)
{
$(this).data("row", index);
}).
click(function()
{
alert($(this).data("row"));
});
$('html').click(function() {
var el = e.target;
alert(el);
});
As people just keep posting code, and no explanations, I will try the other way around...
The click event handler is called in the scope of the clicked element, so you can use the this keyword to access the element. You can use $(this) to get a jQuery object that contains the clicked element, so that you can use jQuery methods on it.
Example:
$(document).ready(function(){
$('ul li').click(function({
var text = $(this).text();
alert('You clicked on the item with the text "' + text + '"');
}));
});
$('li').click(function(){
alert($(this).html());
});
This code will alert one when user will click the one button.

if empty between tag <ul> give alert.?

I want if empty between tag ul alert hello. how is it?
<button class="click">Click</button><p>
<span>
<ul></ul>
</span>
js:
$('.click').click(function() {
if('span ul' == ''){alert('hello')};
});
EXAMPLE: http://jsfiddle.net/KDAwP/1/
Try this using jQuery :empty selector which selects empty elements. An empty element is an element without child elements or text.
$('.click').click(function() {
if($('ul:empty').length){alert('hello')};
});
jQuery is not finding ul inside a span tag. Actually you should not have ul inside a span tag.
Try this fiddle it works perfectly fine.
http://jsfiddle.net/KDAwP/6/
Here:
$('.click').click(function() {
$('div ul').each(function(){
if(this.innerHTML == ''){
alert('hello');
return false;
}
})
});
You cannot have a ul inside of a span
Fiddle: http://jsfiddle.net/Nxk7a/
Tests on the solutions here: jsperf
Another solution which is faster than :empty is:
var isEmpty = jQuery("#foo ul li").length === 0;
But the interesting thing is if you have an id on the ul in question, using the html() is fastest.
var isEmpty = jQuery("#UL_ID").html().length === 0;
So the quickest way really depends on what the selector is.

Categories