Get higher value id of list in jquery - javascript

I have a list:
<ul id="testList">
<li id="3"></li>
<li id="2"></li>
<li id="1"></li>
</ul>
I need get to higher value id of li element with jQuery. In this example it would be, 3. Then append class "last". I tried with each function but don't work.
$('#testList li').each(function(index, li){
//Here obtain a higher value id
$('#testList li').last().addClass('last');
});
I hope someone can help me. Thank you very much!
Regards!

You can use Math.max and map() to get maximum id value and then addClass()
var h = Math.max.apply(null, $('#testList li').map(function() {
return $(this).attr('id');
}))
$('#' + h).addClass('last');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="testList">
<li id="3"></li>
<li id="2"></li>
<li id="1"></li>
</ul>

Probably not the most efficient way, but this would do it:
// initialize the max value to a low number
var max = 0;
// iterate over each li item in the list
$('#testList li').each(function() {
// ensure we have a number
var id = parseInt($(this).prop('id'));
if (! isNaN(id)) {
max = Math.max(max, id);
}
});
// Given that max contains an ID, just pass that in to the selector to add class
$('#' + max).addClass('last');

Related

jquery select by class then match value

I have a list like this
<ul>
<li class="somename">1</li>
<li class="somename">2</li>
<li class="somename">3</li>
<li class="somename">1</li>
</ul>
then I have a value like this
var myvalue = 1;
I want to compare myvalue with all the $(".somename).text() to find the matching ones and change the text of the matching to something else like below
<ul>
<li class="somename">changed</li>
<li class="somename">2</li>
<li class="somename">3</li>
<li class="somename">changed</li>
</ul>
$(".somename").text() give me all the text in a string like 1231
and I tried to for loop
for(i=0;i<$(".somename").length;i++){
if(myvalue == $(".somename")[i].text()){
$(this).text("changed")
}
}
$('.somename').each(function() {
var value = $(this).text();
if (value == "1") {
$(this).text("Changed")
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="somename">1</li>
<li class="somename">2</li>
<li class="somename">3</li>
<li class="somename">1</li>
</ul>
Use .each() to loop through all elements with the class.
Have a condition , if met change the text
When using the bracket object property accessor ([]) on a jQuery object you are accessing the underlying object in the collection so .text() would not be available as that is not a function on the underlying DOM object (you should have seen an error on your console)
You can use jQuery .each method to loop through the collection
$(".somename").each(function(){
//unless you are going to be doing more jQuery DOM stuff
//no need to wrap in jQuery just access the innerText
if(myvalue == this.innerText){
this.innerText = "changed";
}
});
If you dont want to use the .each method and just use the for loop you would need to use either .eq or similar method to get the jQuery wrapped object at a particular index
var elements = $(".somename");
for(i=0;i<elements.length;i++){
let element = elements.eq(i);
if(myvalue == element.text()){
element.text("changed");
}
}
Do like this...
$(".somename").each(function(e, val ){
if (myvalue == e.text){
//do stuff here
}
));
Please try this out but FYI I've not tried this on my own system.
var myvalue = 1;
var lists = document.getElementsByTagName('li');
for(var i = 0; i < lists.length; i++){
if(myvalue == lists[i].innerHTML){
//change your text here
}
}
You can use jQuery .each function.
var myvalue=1;
$('.somename').each(function(){
if($(this).text()==myvalue){
$(this).text('changed');
}
});
Few things here
1. When you search any DOM element .Try to copy it into a variable and then use it .DOM search is a costly operation
2.When you are using for loop,this would point to window object
check the following code snippet
$(document).ready(function(){
var someoneArray=$(".somename");
var someoneArrayLength=someoneArray.length;
var myValue=1;
for(var i=0;i<someoneArrayLength;i++){
var value=parseInt($(someoneArray[i]).text());
console.log(this)
if(myValue == value){
alert("here");
$(someoneArray[i]).text("changed");
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="somename">1</li>
<li class="somename">2</li>
<li class="somename">3</li>
<li class="somename">1</li>
</ul>
Hope this helps

Output data from array in a certain order based on data in the array

I am pushing list items into an array which have a data-sort value on them. When calling them back from the array I need to output them in their data-sort order where 1 would come first, 2 second, and so on. However if the data-sort is equal to 0, I need to do something completely different with the item.
JS
var arr = [];
$('ul li').each(function() {
arr.push($(this));
});
$('ul.main').html('');
$.each(arr, function (i) {
var item = arr[i];
var content = $(item).html();
var itemSort = $(item).data('sort'); //Need to sort by this value
if(itemSort != '0') {
$('ul.main').append('<li>' + content + '</li>')
} else {
$('.another-list').append('<li>' + content + '</li>'); // Sort order of 0's doesn't matter
}
});
HTML
<ul class="main">
<li data-sort="3">Item 1</li>
<li data-sort="2">Item 2</li>
<li data-sort="1">Item 3</li>
<li data-sort="0">Item 4</li>
</ul>
<ul class="another-list"></ul>
The need to create an array from the selected elements is redundant as a jQuery object is an array of the selected elements.
Also, the need to take the html() of an li and then create that in an entirely new li is redundant as you can move elements from one list to another by just using append().
With that in mind you can massively simplify your code by using a combination of sort() and filter():
$('li').sort(function(a, b) {
return $(a).data('sort') > $(b).data('sort');
}).appendTo('.main').filter(function() {
return $(this).data('sort') == 0;
}).appendTo('.another-list');
Example fiddle

Hide same elements in a list

I have a problem I want to solve with jQuery. In a list, I want to check if two items have the same text, and if so I want to delete the second one.
I am not really sure how to go about it.
The markup is simple, kinda like this
<ul>
<li>Text1</li>
<li>Text2</li>
<li>Text1</li>
<li>Text3</li>
<li>Text3</li>
<li>Text4</li>
<ul>
I cannot use an active/inactive class because this list is dynamic and I don't know in advance how it's going to be populated.
Any idea?
$.inArray for a tmp array would work.
$(document).ready(function(){
var tmparr = [];
$('.list li').each(function(i,item){
if($.inArray($(this).text(), tmparr) >= 0){
$(this).remove();
}else{
tmparr.push($(this).text());
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list">
<li>Text1</li>
<li>Text2</li>
<li>Text1</li>
<li>Text3</li>
<li>Text3</li>
<li>Text4</li>
<ul>
You can achieve this e.g. like this:
var unique = {};
$('li').each(function() {
var txt = $(this).text();
if (unique[txt])
$(this).remove();
else
unique[txt] = true;
});
Fiddle
As explanation: unique is initialized as object. While each() iterates over all li elements, the if (unique[txt]) is true in case it was previously set to true for the text of the li currently processed. In this case the current li will be removed. If not, unique[txt] for the text of the current li is set to true and added to unique. As it might not be clear what unique finally contains: { Text1=true, Text2=true, Text3=true, Text4=true }
You will need to iterate over your li elements and store their text in an array. If the text for the ith element is already in the array, skip it. Once you have an array of unique text strings, remove all li elements and generate new ones from the information in your array.
http://jsfiddle.net/k255o52e/1/
$('ul li').each(function () {
var txt = $(this).text();
// finds all LI that contain the same text
// excludes the first element
var $li = $('li:contains("' + txt + '"):not(:first)');
// and removes the other
$li.remove();
})
UPDATE:
$('ul li').each(function () {
var txt = $(this).text();
var $li = $('li:contains("' + txt + '"):not(:first)').filter(function(index)
{
return $(this).text() === txt;
});
$li.remove();
})

How to find number of <ul> inside each div

I have a large file of this form [similar div's throughout]. I want to be able to select a div, find the number of ul's in it and traverse through each of them to get value of each li in it.
<div class="experiment">
<div class="experiment-number">5</div>
<ul class="data-values">
<li><div></div> 14</li>
<li><div></div> 15</li>
</ul>
<ul class="data-values">
<li><div></div> 16</li>
</ul>
</div>
I have tried looping through all experiment divs, then select the uls, but it selects all the ul in the page, not only the ones under current div.
$('experiment ul').eq('$i');
Your HTML is currently incorrect, since you're simply starting new <div> and <ul> elements rather than closing the existing ones. Ignoring that because it's trivial to fix, we'll move on to the real issue.
You need to select all of the <div class="experiment"> elements, then iterate through them. To do that you can use the .each() function. It might look something like this:
var experiments = $('.experiment'); // all of them
experiments.each(function(i, val) { // will iterate over that list, one at a time
var experiment = $(this); // this will be the specific div for this iteration
console.log("Experiment: " + experiment.find('.experiment-number').text());
// outputs the experiment number
console.log("Experiment ULs: " + experiment.find('ul').length);
// number of <ul> elements in this <div>
var total = 0;
experiment.find('ul.data-values li').each(function() {
total += parseInt($(this).text(), 10);
});
console.log("Experiment total: " + total);
// outputs the total of the <li> elements text values
});
Take a look at this jsFiddle demo.
to get all the ul inside div.experiment
var ul = $('.experiment').find('ul');
and to get all li elements inside each ul found above
ul.each(function(list) {
var li = $(list).find('li');
});
$('.experiment').each(function() {
var cnt = $(this).children('ul').length;
$(this).find('.experiment-number').text(cnt);
});
First of all you need to work out the correct selector for each DIV.
The selector you want is:
".experiment"
Notice the . to denote a class selector.
This will allow you access to each DIV element. If you then want to loop though each of these, you can do so like this:
$(".experiment").each(function(){
var div = $(this);
var elementsInThisDiv = div.find("ul");
//you now have a list of all UL elements in the current DIV only
var numberOfElements = elementsInThisDiv.length;
//you now have a count of UL elements belonging to this DIV only
//you can loop the UL elements here
$(elementsInThisDiv).each(function(){
var ul = $(this);
//do something with the UL element
//like get the LI elements...
var liElements = ul.find("li");
});
});
IMPORTANT: There is also an error with your HTML, you need to close your <ul> elements correctly using </ul>

jQuery Find and List all LI elements within a UL within a specific DIV

I have 3 Columns of ULs each a Dynamic UL container that can have anywhere from 0-9 LI containers (eventually more). All my LI elements have an attribute "rel" which I am trying to ultimately find that attribute and use it for something else on all LI elements within that parent DIV. I do eventually want to find more based on each but for not the very least the rel.. Any Ideas how I can achieve that with jQuery? Example:
<ul id="column1">
<li rel="1">Info</li>
<li rel="2">Info</li>
<li rel="3">Info</li>
</ul>
<ul id="column2">
<li rel="4">Info</li>
<li rel="5">Info</li>
<li rel="6">Info</li>
</ul>
<ul id="column3">
<li rel="7">Info</li>
<li rel="8">Info</li>
<li rel="9">Info</li>
</ul>
these elements are all sortable as well. So when I get a list of them I want to also keep them in the order they were found from top to bottom of each column.
I have tried find(), parent(), and similar, maybe I am approaching it wrong. But its still worth mentioning to help come up with an idea
Are you thinking about something like this?
$('ul li').each(function(i)
{
$(this).attr('rel'); // This is your rel value
});
var column1RelArray = [];
$('#column1 li').each(function(){
column1RelArray.push($(this).attr('rel'));
});
or fp style
var column1RelArray = $('#column1 li').map(function(){
return $(this).attr('rel');
});
html
<ul class="answerList" id="oneAnswer">
<li class="answer" value="false">info1</li>
<li class="answer" value="false">info2</li>
<li class="answer" value="false">info3</li>
</ul>
Get index,text,value
js
$('#oneAnswer li').each(function (i) {
var index = $(this).index();
var text = $(this).text();
var value = $(this).attr('value');
alert('Index is: ' + index + ' and text is ' + text + ' and Value ' + value);
});
$('li[rel=7]').siblings().andSelf();
// or:
$('li[rel=7]').parent().children();
Now that you added that comment explaining that you want to "form an array of rels per column", you should do this:
var rels = [];
$('ul').each(function() {
var localRels = [];
$(this).find('li').each(function(){
localRels.push( $(this).attr('rel') );
});
rels.push(localRels);
});

Categories

Resources