jquery select by class then match value - javascript

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

Related

Is there any programmtical way where I can remove class of list item

I am doing one loop where I am matching with some value and assigning class="hidden" to list. But When I run again the loop I want all my list should be without class, so I can assign for other value.
Here is my code.
for (i = list.children.length; i--;) {
li = list.children[i];
match = li.textContent.toLowerCase().indexOf(value.toLowerCase()) > -1;
li.classList.toggle('hidden', !match)
}
But before I run this loop I want all the list without any class so hete in the list I want to remove Class="hidden"
<li class="hidden">
Albania
</li>
Can anyone help me to achieve this
You want to do this before your existing loop? Try this:
var list = document.getElementById("list");
for (i = list.children.length; i--;) {
li = list.children[i];
li.classList.remove("hidden");
}
<ul id="list">
<li class="hidden">foo</li>
<li>bar</li>
<li class="hidden">baz</li>
</ul>
Though it does look like you could do this in the beginning of your existing loop. No need for another loop before that one.
Why not use a combo of Element.classList.contains(), ..remove(), ..add() etc. Lots of info on the MDN page.
For example:
for(i=list.children.length; i--;) {
li = list.children[i];
if (li.textContent.toLowerCase().indexOf(value.toLowerCase()) > -1) {
li.classList.add('hidden');
// or is it li.classList.remove('hidden'); here?
}
}
It is safe to ..add() even if the element has the class already. The class will not be added twice.

Get higher value id of list in jquery

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');

.text() not returning value

I'm using this code to create a <ul><li> of the classes attached to the div .lista-produtos.
$(document).ready(function(){
var alts = {};
$('.lista-produtos').each(function(){
var classes2 = $(this).attr('class').split(' ');
for (var i = 0; i < classes2.length; i++) {
var matches2 = /^tipo\-(.+)/.exec(classes2[i]);
if (matches2 != null) {
var produto = matches2[1];
}
}
if(!alts[classes2]){
alts[classes2] = true;
$('ul.filters').append('<li class="filter-produto">'+ produto +'</li>');
}
});
});
The code above generates <li>s inside of the <ul class="filters">. So the code is something like this:
<ul class="filters">
<li class="filter-produto active">Produto 1<li>
<li class="filter-produto">Produto 2<li>
<li class="filter-produto">Produto 3<li>
<li class="filter-produto">Produto 4<li>
</ul>
As you can see, one of the <li>s will have an additional class named "active", and the problem is I need to get the text inside of it (Produto 1) to use on another code but it's not working:
var produto2 = $('li.filter-produto.active').text();
I tested alert(produto2); to see if the code worked but it only returns a blank value and not the text inside the <li>.
Sadly I don't have rep to comment, but can you show us the order of the stuff happening?
Perhaps you are asking for the value before the active class it attached to the li. Something like this:
// Function to create the ul and lis
var produto2 = $('li.filter-produto.active').text();
// Function that adds the active class
So maybe the li.filter-produto.active doesn't exist when you ask for it's value?

Selecting a particular DOM element using JavaScript

I have the following code in my HTML:
<li class="strange">1</li>
<li class="strange">2</li>
<li class="strange">3</li>
<li class="strange">4</li>
I want to choose the exact <li> which contains number '3' as a Text.
Is there any method to choose the exact element?
Can we choose by using some OO-JS methods?
try using jQuery selector :contains
Description: Select all elements that contain the specified text.
$('li:contains("3")')
DEMO
Match exact text
As per #Raoulito mention in his comment here updated answer which match exact text using jQuery filter().
Description: Reduce the set of matched elements to those that match
the selector or pass the function's test.
$(document).ready(function(){
$("li").filter(function() {
return $(this).text() === "3";
}).css("color", "red");
});
DEMO
Try with jQuery contains
$('li:contains("3")');
Demo
Using JavaScript you can do like:
var list = document.getElementsByClassName("strange");
for (i = 0; i < list.length; i++) {
if(list[i].innerHTML ==3)
{
list[i].style.color = "blue";
list[i].style.backgroundColor = "red";
}
}
Check Fiddle.
If you want to use just javascript you can do something like that:
HTML
<ul id="ul">
<li class="strange">1</li>
<li class="strange">2</li>
<li class="strange">3</li>
<li class="strange">4</li>
</ul>
Javascript
var nums = document.getElementById("ul"); // get the ul element
var listItem = nums.getElementsByClassName("strange"); //fetch all elements inside the ul that have a class of strange
var element;
// loop through the list elements
for (var i=0; i < listItem.length; i++) {
// check whether list's inner html is equal to 3
if (parseInt( listItem[i].innerHTML) == 3) {
// set the value of element equal to the list element
element = listItem[i];
break;
}
}
console.log(element); // logs out the element that has the required value, you can use element.innerHTML to check
This only select the element which has exactly '3' as text:
$('li.strange').each(function() {
if ( $(this).text() == '3' ) {
$(this).css('color','red');
}
});
http://jsfiddle.net/dremztou/1/
$('li.strange:contains("3")').addClass('selected'); would select all the elements containing 3, including 13, 23, 33, etc.

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

Categories

Resources