How to check last element has a css class or not? - javascript

I am adding class to these elements one by one based on user input. When I reached the last span element of this section, i need to give pop up. How to check that this last span has added a css class?
<section id="word-section"><span class="incorrect-word-c">ਪਰਕੋ</span><span class="current-word">ਚੇਤਕ</span><span>ਚਰਚ</span><span>ਪਰਕ</span><span>ਰੋਕ</span><span>ਰੇਤ</span><span>ਕਰੋ</span><span>ਚਟਪਟ</span><span>ਤਕ</span><span>ਰੁਤ</span><span>ਚਰਚ</span><span>ਰੋਕੋ</span><span>ਰਕਤ</span><span>ਰੋਕ</span><span>ਚਰਚ</span><span>ਪਰਕ</span><span>ਰੇਤ</span><span>ਪਰਕ</span><span>ਪਰਕ</span><span>ਪਰਤ</span><span>ਕਿ</span><span>ਰੋਕ</span><span>ਚੋਕਰ</span><span>ਰਕਤ</span><span>ਕਿ</span><span>ਰੋਕੋ</span><span>ਰੇਤ</span></section>

var remaining = $('#word-section > span').not('.current-word').length;
This command will find all spans that are direct children of the word-section section. It then filters to only include those that do not have the current-word class, and get the length (count) of them.
If remaining is zero, they all have the class.

To answer the specific question
Check if last element has a css class or not
you can use:
$("#word-section > span:last").hasClass("current-word")
this will:
find word-section
get all direct-descendant spans
limit the spans to the last one :last
check if that last one has class current-word
There's lots of different ways to do this, eg:
$("#word-section").find(">span").last().is(".current-word")
$("#word-section > span.current-word:last").length == 1
$("#word-section > span.current-word").nextAll().length == 0
Example snippet:
if ($("#word-section > span:last").hasClass("current-word")) {
// show popup
console.log("example: last word is current-word");
}
else {
console.log("example: more words to go");
}
if ($("#word-section-sample2 > span:last").hasClass("current-word")) {
// show popup
console.log("sample2: last word is current-word");
}
else {
console.log("sample2: more words to go");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="word-section"><span class="incorrect-word-c">ਪਰਕੋ</span><span class="current-word">ਚੇਤਕ</span><span>ਚਰਚ</span><span>ਪਰਕ</span><span>ਰੋਕ</span><span>ਰੇਤ</span><span>ਕਰੋ</span><span>ਚਟਪਟ</span><span>ਤਕ</span><span>ਰੁਤ</span><span>ਚਰਚ</span><span>ਰੋਕੋ</span><span>ਰਕਤ</span><span>ਰੋਕ</span><span>ਚਰਚ</span><span>ਪਰਕ</span><span>ਰੇਤ</span><span>ਪਰਕ</span><span>ਪਰਕ</span><span>ਪਰਤ</span><span>ਕਿ</span><span>ਰੋਕ</span><span>ਚੋਕਰ</span><span>ਰਕਤ</span><span>ਕਿ</span><span>ਰੋਕੋ</span><span>ਰੇਤ</span></section>
<section id="word-section-sample2"><span class="incorrect-word-c">ਪਰਕੋ</span><span>ਚੇਤਕ</span><span>ਚਰਚ</span><span>ਪਰਕ</span><span>ਰੋਕ</span><span>ਰੇਤ</span><span>ਕਰੋ</span><span>ਚਟਪਟ</span><span>ਤਕ</span><span>ਰੁਤ</span><span>ਚਰਚ</span><span>ਰੋਕੋ</span><span>ਰਕਤ</span><span>ਰੋਕ</span><span>ਚਰਚ</span><span>ਪਰਕ</span><span>ਰੇਤ</span><span>ਪਰਕ</span><span>ਪਰਕ</span><span>ਪਰਤ</span><span>ਕਿ</span><span>ਰੋਕ</span><span>ਚੋਕਰ</span><span>ਰਕਤ</span><span>ਕਿ</span><span>ਰੋਕੋ</span><span class="current-word">ਰੇਤ</span></section>

Related

"[i - 1]" is Not Getting the Last Element of a List (JavaScript)

The Problem:
Hey everyone. I'm trying to create a simple function that identifies the next and previous elements of a current item within the ".length" of elements in a div, and then changes the ID of those two elements. Everything is working except for the part where it tries to identify the previous element at the beginning and the next element at the end.
What I've Tried:
It used to be that it would identify those items by using ".nextElementSibling" and ".previousElementSibling", but I realized that since it starts at the first element within the div then it would begin leaking out and trying to identify the previous element outside of the div. I decided to use a for loop that creates a list of the elements with the specific class name, which works as intended. It begins to run into issues again, though, when it reaches the beginning or the end of the list. I assumed that "[i - 1]" would automatically bring it to the last element if the current was the one at the beginning of the list, and that "[i + 1]" would automatically bring it to the first element if the current was the one at the end of the list. It seems that is not the case.
Is anyone able to help me figure this out? It would be much appreciated.
Note: For the sake of simplicity, I didn't include the JavaScript code that makes it switch between items within the div. That part is fully functional so I don't believe it should affect the underlying concept of this problem.
My Code:
HTML:
<div class="items">
<div id="current-item" class="current-div-item"></div>
<div id="item" class="div-item"></div>
<div id="item" class="div-item"></div>
<div id="item" class="div-item"></div>
<div id="item" class="div-item"></div>
</div>
Javascript:
var divItems = document.getElementsByClassName('div-item'); // Gets number of elements with the specific class.
for (i = 0; i < divItems.length; i++) { // Creates list of elements with the specific class.
if (divItems[i].classList.contains('current-div-item')) { // If it is the current item, then do this:
var next = divItems[i + 1] // Find the next element in the list
var previous = divItems[i - 1] // Find the previous element in the list
next.id = 'next-item' // Change the next element's ID to "next-item"
previous.id = 'previous-item' // Change the previous element's ID to "previous-item"
}
}
You are wanting the items to wrap around that isn't going to happen. For the first item the previous item will be index -1 and for the last item the next index will be 1 larger than the actual number of items in the array.
If you add in a ternary you can get the values to wrap.
var prevIndex = (i === 0) ? divItems.length - 1 : i - 1;
var nextIndex = (i === divItems.length - 1) ? 0 : i + 1;
var next = divItems[prevIndex] // Find the next element in the list
var previous = divItems[nextIndex] // Find the previous element in the list
Based on your HTML code, in logic JS to fetch the all the items based in class it would not fetch the current-div-item as you have written logic to fetch only div-item. So I assume that you also need to change the HTML code. As per my understanding about your requirement I have done some changes and uploading the modified code. Which is working as per you requirement.
HTML:
<div id="current-div-item" class="div-item">Current</div>
<div id="item" class="div-item">Div1</div>
<div id="item" class="div-item">Div2</div>
<div id="item" class="div-item">Div3</div>
<div id="item" class="div-item">Div4</div>
Java Script:
var divItems = document.getElementsByClassName('div-item'); // Gets number of elements with the specific class.
for (i = 0; i < divItems.length; i++) {
if (divItems[i].id=='current-div-item') {
var next;
if (i == divItems.length-1)
next = divItems[0];
else
next = divItems[i + 1];
var previous;
if (i == 0)
previous=divItems[divItems.length-1];
else
previous = divItems[i - 1] // Find the previous element in the list
next.id = 'next-item' // Change the next element's ID to "next-item"
previous.id = 'previous-item' // Change the previous element's ID to "previous-item"
}
}
Attached the screenshot of the modified elements id for your reference

Javascript live search not responding?

Trying to create a live search using javascript and it seems as if the script is not responding. I have the script within a .js file and I have added it at the end of the page.
The functionality I want is when the user types into #PokemonSearch it will hid irrelevant pokemon-selector-item divs
What happens when I type into #PokemonSearch with the following code? Absolutely nothing.
$(document).ready(function(){
$("#PokemonSearch").keyup(function(){
// Retrieve the input field text and reset the count to zero
var filter = $(this).val(), count = 0;
// Loop through the comment list
$(".pokemon-selector-item").each(function(){
// If the list item does not contain the text phrase fade it out
if ($(this).attr(".pokemon-name").text().search(new RegExp(filter, "i")) < 0) {
$(this).fadeOut();
// Show the list item if the phrase matches and increase the count by 1
} else {
$(this).show();
count++;
}
});
});
});
HTML Selector item example:
<div class="pokemon-selector-item">
<img class="pokemon-image" src="~/assets/images/pokemon/pokemon-50x50/charmander.png" />
<div class="pokemon-selector-info">
<span class="pokemon-name">Charmander</span>
<span class="pokemon-type">Fire Pokemon</span>
</div>
</div>
You have a typo. .attr(".pokemon-name") on line 11 should be .find(".pokemon-name")

How to delete current element if previous element is empty in jquery?

I want to delete element with class "tehnicneinfo" but only if the element I'm checking ( with class "h2size") has no child. I have a bunch of those elements, generated by a plugin and I want to delete only the ones that have the next element without child. I wrote jquery code, but it delets all of my elements, not only the ones that have the next element without child. Here is my jquery code:
$('.news .h2size > div').each(function() {
var ul = $(this).find('ul');
if(!ul.length) $(this).remove();
var h1 = $('.news').find('.tehnicneinfo');
var h2size = $('.news').find('.h2size');
if(h2size.prev().is(':empty'))
{
h1.remove();
}
});
this code is inside $(document).ready(function(). Can you tell me what I'm doing wrong? The code is for something else also, so I'm having truble only from var h1 = $('.news').find('.tehnicneinfo'); this line on. Thanks in advance!
Html:
<div class="news">
<h1 class="tehnicneinfo">xxx</h1>
<div class="h2size">
<div id="xyxyxy">
.......
</div>
</div>
<h1 class="tehnicneinfo">yyy</h1>
<div class="h2size"></div>
....
</div>
That's the html, only that there is like 20 more lines that are the same, but with different values (not yyy and xxx). I would need to delete all 'yyy' (they are not all with same value).
You can use filter to filter the ones you want to remove then remove them
"I want to delete only the ones that have the next element without child"
$('.tehnicneinfo').filter(function(){
return !$(this).next().children().length;
// only ones with next sibling with no children
}).remove();
JSFIDDLE

How can I show/hide divs dynamically (on KeyUp, iTunes style) using Javascript/jQuery and a text or search field with case insensitive

I set out on a journey to create an iTunes-like search using Javascript. I learned about jQuery, and with some help from people on StackOverflow, I was successful.
I've come back here to share with you a very simple way to create a dynamic hide/show list based on the user input.
Let's search!
The entirety of the tutorial code can be found here.
And a JSFiddle for it is here!
So good to see Nick was successful on this experiment. good job on learning how to do it :)
Just in case you haven't encountered this jquery plugin, you might want to take a look at it too it's called Quick search.
https://github.com/riklomas/quicksearch
And I've used it on numerous pages and it works like a charm. example:
http://fedmich.com/works/types-of-project.htm
First, create a simple Div Layout with some text in the divs and search bar above it.
<div class="search_bar">
<form><!--The Field from which to gather data-->
<input id="searchfield" type="text" onclick="value=''" value="Case Sensitive Search">
</form>
</div>
<!--Containers With Text-->
<div class="container">
<div class="container_of_hc">
<div class="horizontal_containers">Cat</div>
<div class="color">Black</div>
<div class="color">White</div>
<div class="color">Orange</div>
</div>
<div class="horizontal_containers">Dog</div>
<div class="horizontal_containers">Rat</div>
<div class="horizontal_containers">Zebra</div>
<div class="horizontal_containers">Wolf</div>
</div>
CSS:
.container {
width: 100%;
}
.horizontal_containers {
height:10%;
border: solid 3px #B30015;
font-size: 45px;
text-align: center;
}
Second, you will make a script utilizing jQuery. Remember the title says this is a Dynamic Search, meaning (for us) we want to update the search with each key typed:
$("#searchfield").keyup(function() {
Note: Need a selector refresher?
Then we will set a variable to the value in #searchfield:
var str = $("#searchfield").val(); //get current value of id=searchfield
To ensure we show all the divs in our list when there is nothing in the searchfield we create an if statement based on the length of our new variable (str):
if (str.length == 0) {
//if searchfield is empty, show all
$(".horizontal_containers").show();
}
Last, we do the actual hiding of the divs if the length of str is not 0:
else {
//if input contains matching string, show div
//if input does not contain matching string, hide div
$("div:contains('" + str + "').horizontal_containers").show();
$("div:not(:contains('" + str + "')).horizontal_containers").hide();
}
});
The div:contains() and div:not(:contains()) statements are what set the conditions. It's essentially an if statement. They search the text contained within the div, not the div attributes. If you want to search a deeper div structure you can use more than one selector in the script's jQuery statements like so:
if (str.length == 0) {
//if searchfield is empty, show all
$(".container .color").show();
} else {
//if input contains matching string, show div
//if input does not contain matching string, hide div
$(".container div:contains('" + str + "').color").show();
$(".container div:not(:contains('" + str + "')).color").hide();
}
Replace the script statement you already have to give it a try.
Note: The nesting structure of your divs must match that in your selector.
And that's essentially it. If you have tips to improve this, know how to change it to a case insensitive search, or anything else you can think of, please let me know!
Thanks to MrXenoType I have learned case insensitivity for the :contains function.
To create a case insensitive search for this project simply add:
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
This creates a pseudo for the contains function. Place this code above your other script (within the same script) to make true for only this script.
Try:
$.expr[":"].contains_nocase = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
for adding a :contains_nocase() selector with jQuery 1.8

CSS class depending on list items text length

Is there a way to set different classes to items in a list depending on the length of the value? Preferrably plain JS or jQuery.
I have a list with fixed width, and the text amount in each list item varies. The list items has backgrounds which can't be repeated or extend, and because of that I would need to make different backgrounds (classes) for different text lengths.
1-15 chars would be taken care of by the default css class, 15-30 chars would need an extra class with the extended background and 30-45 chars would need another class etc.
Being a total n00b in JS I just can't manage to figure this out, even though I've been fiddling with it for the last two days...
Thanks a lot in advance,
Eirik.
$('#myList li').each(function() {
var length = ($(this).html().length);
if (length > 30) {
$(this).addClass('longest');
}
else if (length > 15) {
$(this).addClass('long');
}
else {
$(this).addClass('default');
}
});
Working example here.
$('.listItem').each(function(){
var content = $(this).html();
if(var.length > 30){
$(this).addClass('Over30');
}
.....etc
Set this to run after the content has loaded e.g.
$(document).ready(function () {
$('.listItem').each(function(){
var content = $(this).html();
if(var.length > 30){
$(this).addClass('Over30');
}
.....etc
}

Categories