JQuery get a contiguous sequence of elements - javascript

I'm trying to get a contiguous array of elements using JQuery. For example for the this html:
<div class="parent">
<div class="childType2">1</div>
<div class="childType2">2</div>
<div class="childType2">3</div>
<div class="childType1">4</div>
<div class="childType1">5</div>
<div class="childType1">6</div>
<div class="childType1">7</div>
<div class="childType2">8</div>
<div class="childType1">9</div>
<div class="childType1">10</div>
<div class="childType1">11</div>
<div class="childType1">12</div>
</div>
I want it to return the div's containing 4,5,6,7 (The first sequnce of the divs with the class="childType1").
I tried to do
$("<div>test</div>")($('.parent .childType2').siblings('.childType1').addBack());
But this of course will add the div with the text test after the last childType1 (12).
I'm not so good with JQuery.
Edit:
Since the div's are dynamically generated, I ended up adding for each "group" a special class post-fix of the id related to his group, and used the method described in suspectus's answer. Not exactly what i had in mind, but it works :D.

You can use either .each (docs) or .filter (docs). If you use .filter() you can chain another jQuery method after it.
var state = 0;
var elements = [];
$('.parent div').each( function( i, elem ) {
if( state != 2 && elem.className === "childType1" ) {
state = 1;
elements.push( elem );
} else if ( state == 1 ) {
state = 2;
}
} );
console.log( elements );
Or more jQuery approach:
var state = 0;
$('.parent div').filter( function() {
if( state != 2 && $(this).hasClass( "childType1" ) ) {
state = 1;
return true;
} else if ( state == 1 ) {
state = 2;
}
return false;
} ).css( 'background-color', 'red' );

<div class="parent">
<div class="childType2">1</div>
<div class="childType2">2</div>
<div class="childType2">3</div>
<div class="childType1 inner">4</div>
<div class="childType1 inner">5</div>
<div class="childType1 inner">6</div>
<div class="childType1 inner">7</div>
<div class="childType2">8</div>
<div class="childType1">9</div>
<div class="childType1">10</div>
<div class="childType1">11</div>
<div class="childType1">12</div>
</div>
$(".inner") // gives the elements required

You could use filter for this :
var $elements = $(".childType1").filter(function() {
var no = parseInt($(this).text(), 10)
return (( no > 3) && ( no < 8))
});
now $elements will contain only those matched elements between 3 and 8 ie., 4 to 7.

You can use .each() method for looping all the divs having class="childType1"
Following is the complete code. Modify it according to your need.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$(".childType1").each(function (i) {
if ( $(this).html() == "4" ||$(this).html() == "5" || $(this).html() == "6" ||$(this).html() == "7") {
alert($(this).html());
}
});
});
</script>
</head>
<body>
<div class="parent">
<div class="childType2">1</div>
<div class="childType2">2</div>
<div class="childType2">3</div>
<div class="childType1">4</div>
<div class="childType1">5</div>
<div class="childType1">6</div>
<div class="childType1">7</div>
<div class="childType2">8</div>
<div class="childType1">9</div>
<div class="childType1">10</div>
<div class="childType1">11</div>
<div class="childType1">12</div>
</div>
</body>
</html>

Related

shorter way to check if a title exists

Checking if a title already exists. Is there a shorter way? Something like:
if(test.exists.inside('.title'){...
var x = 0;
var test = $('#test').text();
$('.title').each(function(){
if($(this).text() == test){x = 1;}
});
if(x == 1){console.log('exists');}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='title'>lorem</div>
<div class='title'>ipsum</div>
<div class='title'>lorema</div>
<div class='title'>ipsuma</div>
<div id='test'>lorem</div>
a lot of ways to do this :contains , filter() with indexOf() and filter() with text equal test.. depending on what you're trying to do
var x = 0;
var test = $('#test').text();
var Exists = $('.title:contains("'+test+'")').length;
console.log('Yes '+Exists+ ' title with text '+test);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='title'>lorem</div>
<div class='title'>ipsum</div>
<div class='title'>lorema</div>
<div class='title'>ipsuma</div>
<div id='test'>lorem</div>
you can check also with for contains text check
$('.title:contains("'+test+'")').length > 0
OR for exact text check
$('.title').filter(function(){
return $(this).text().trim() == test;
}).length > 0
Note: :contains and .indexOf search for the text contains text not the exact text .. by using $(this).text().trim() == test; this
will return the exact text element
If you're just looking for shorter code, one option would be to invoke Array.prototype.some, and rather than store the result of .text() in a variable, invoke it every time, to save on characters typed:
if ([].some.call($('.title'), d => $(d).text() === $('#test').text())) {
console.log('exists');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='title'>lorem</div>
<div class='title'>ipsum</div>
<div class='title'>lorema</div>
<div class='title'>ipsuma</div>
<div id='test'>lorem</div>
Personally, I'd prefer readability over code length:
const textToFind = $('#test').text();
const exists = Array.prototype.some.call(
$('.title'),
title => $(title).text() === textToFind
);
if (exists) {
console.log('exists');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='title'>lorem</div>
<div class='title'>ipsum</div>
<div class='title'>lorema</div>
<div class='title'>ipsuma</div>
<div id='test'>lorem</div>

change color of div depending numeric value jquery

I have 15 divs with the same class but different id and i want to change the color of the value.
For example, if one or five div's value is under 15 the color of the value will be red, if three or one the value of it is up to 15 but under 45 the color of the value is green and if the value of the div is up to 45 the color will be yellow but all of the colors i want to see at the same time.
My div's are like this:
<div id="listado">
<div id="cuautitlan" class="dfedo">15</div>
<div id="coacalco" class="dfedo">54</div>
<div id="atizapan" class="dfedo">65</div>
<div id="tlalne" class="dfedo">2</div>
<div id="tlalne2" class="dfedo">5</div>
<div id="naucalpan" class="dfedo">90</div>
<div id="neza" class="dfedo">105</div>
<div id="huixqui" class="dfedo">65</div>
<div id="azca" class="dfedo">75</div>
<div id="gustavo" class="dfedo">45</div>
<div id="miguel" class="dfedo">35</div>
<div id="cuauh" class="dfedo">2</div>
<div id="venus" class="dfedo">1</div>
<div id="coaji" class="dfedo">58</div>
<div id="alvaro" class="dfedo">5</div>
<div id="benito" class="dfedo">95</div>
<div id="izta" class="dfedo">43</div>
<div id="magda" class="dfedo">35</div>
<div id="coyoacan" class="dfedo">33</div>
<div id="iztapa" class="dfedo">65</div>
<div id="tlalpan" class="dfedo">89</div>
<div id="xochi" class="dfedo">99</div>
<div id="tlahuac" class="dfedo">9</div>
<div id="milpa" class="dfedo">0</div>
</div>
My jquery is like this
$("div.dfedo").each(function()
{
$(this).value < 15 ? $(this).css('color','red');
});
My fiddle
Make this jQuery plugin:
$.fn.colorize = function () {
return this.each(function() {
var $this = $(this), number = $this.text();
$this.css({color: number < 15 ? "red"
: number < 45 ? "green"
: "yellow"});
});
};
And just run:
$("div.dfedo").colorize();
See DEMO.
Making a jQuery plugin for things like these is a good habit. That way you can reuse your code easily and do interesting things like this:
$("div.dfedo").hide().colorize().show("slow");
By making a simple plugin you basically make a new jQuery command that does what you want.
Please check the demo :
https://jsfiddle.net/pj4c40qq/1/
$("div.dfedo").each(function() {
$(this).html() < 15 ? $(this).css('color', 'red') : null;
($(this).html() >= 15 && $(this).html() < 45) ? $(this).css('color', 'green'): null;
$(this).html() >= 45 ? $(this).css('color', 'yellow') : null;
});
Your issue was on the Conditional (ternary) Operator:
$('div.dfedo').each(function() {
var $elem = $(this),
val = $elem.html(),
color = (val < 15)
? 'red'
: (val >= 15 && val < 45)
? 'green'
: 'yellow';
$elem.css('color', color);
});
.dfedo {
background-color: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="listado>
<div id="cuautitlan" class="dfedo">15</div>
<div id="coacalco" class="dfedo">54</div>
<div id="atizapan" class="dfedo">65</div>
<div id="tlalne" class="dfedo">2</div>
<div id="tlalne2" class="dfedo">5</div>
<div id="naucalpan" class="dfedo">90</div>
<div id="neza" class="dfedo">105</div>
<div id="huixqui" class="dfedo">65</div>
<div id="azca" class="dfedo">75</div>
<div id="gustavo" class="dfedo">45</div>
<div id="miguel" class="dfedo">35</div>
<div id="cuauh" class="dfedo">2</div>
<div id="venus" class="dfedo">1</div>
<div id="coaji" class="dfedo">58</div>
<div id="alvaro" class="dfedo">5</div>
<div id="benito" class="dfedo">95</div>
<div id="izta" class="dfedo">43</div>
<div id="magda" class="dfedo">35</div>
<div id="coyoacan" class="dfedo">33</div>
<div id="iztapa" class="dfedo">65</div>
<div id="tlalpan" class="dfedo">89</div>
<div id="xochi" class="dfedo">99</div>
<div id="tlahuac" class="dfedo">9</div>
<div id="milpa" class="dfedo">0</div>
</div>

jquery not getting class name of elements

I have the following code but for some reason jQuery does not pick the elements class name, I understand that if the element has more than one class calling .attr('class') won't return them but the .hasClass('class-name') should be able to identify if the element has the class name.
My problem is that jquery returns class name as undefined(I got this from the line commented.).
How can I make the all other div children of the #parent, that do not have class the-one to have a yellow background.
$(document).ready(function()
{
var j = $('#parent> div').size();
for(var i =0;i<j;i++)
{
//alert($('#parent> div').children().eq(i).attr('class'));
if(!$('#parent> div').children().eq(i).hasClass('the-one'))
{
$('#parent> div').children().eq(i).css('background','yellow')
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id = "parent">
<div class = "one the-one">one</div>
<div class = "two">two</div>
<div class = "three">Three</div>
<div class = "four">Four</div>
</div>
The children() call is redundant as none of the div elements have any child elements. Remove that and the code works:
$(document).ready(function() {
var j = $('#parent> div').size();
for (var i = 0; i < j; i++) {
//alert($('#parent> div').eq(i).attr('class'));
if (!$('#parent> div').eq(i).hasClass('the-one')) {
$('#parent> div').eq(i).css('background', 'yellow')
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="parent">
<div class="one the-one">one</div>
<div class="two">two</div>
<div class="three">Three</div>
<div class="four">Four</div>
</div>
Also note that you can tidy the logic in your JS using each() with the this keyword to reference the element in the loop:
$('#parent > div').each(function() {
if ($(this).hasClass('the-one'))
$(this).css('background', 'yellow')
});
The problem is $('#parent> div') returns the div children of #parent so calling children() again does not return any elements.
You can use a simple jQuery selector instead of a loop like
$(document).ready(function() {
$('#parent> div:not(.the-one)').css('background', 'yellow')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="parent">
<div class="one the-one">one</div>
<div class="two">two</div>
<div class="three">Three</div>
<div class="four">Four</div>
</div>
But you can just use css for this, no need to use jQuery
#parent> div:not(.the-one) {
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="parent">
<div class="one the-one">one</div>
<div class="two">two</div>
<div class="three">Three</div>
<div class="four">Four</div>
</div>
$(document).ready(function() {
$('#parent > div').each(function(){
var classtheone = $(this).hasClass('the-one');
if(!classtheone){
$(this).css('background-color', 'yellow')
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id = "parent">
<div class = "one the-one">one</div>
<div class = "two">two</div>
<div class = "three">Three</div>
<div class = "four">Four</div>
</div>
Try this way
Why not try a simpler method?:
$("#parent > div").not(".the-one").css("background", "yellow");
More info about jQuery's .not method...
Try this
$("#parent div").each(function(){
var me=$(this);
if(me.hasClass("the-one")) { me.css({"background-color" : "yellow"}); }
})
As written already in other answers, your children() call is the problem, I suggest using the following solution with each() as it is simpler
$(document).ready(function()
{
$('#parent div').each(function( i ) {
if ( !$(this).hasClass('the-one')) {
$(this).css('background','yellow');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id = "parent">
<div class = "one the-one">one</div>
<div class = "two">two</div>
<div class = "three">Three</div>
<div class = "four">Four</div>
</div>

tSort on jQuery object

I'm trying to sort the results of a jQuery selection with tSort.
HTML:
<div sort="2"></div>
<div sort="3"></div>
<div sort="1"></div>
<div sort="4"></div>
<div sort="6"></div>
<div sort="5"></div>
Javascript:
<script>
$sort_order = $('div').tsort({attr:'sort'});
</script>
I want the result to be: 1,2,3,4,5,6 in the jQuery object, not yet inserted into the page.
Is this possible with tSort, or should I write my own algorithm?
It is easier to do it if there is a wrapper of all the div elements.
HTML:
<div id="wrapper">
<div sort="2">2</div>
<div sort="3">3</div>
<div sort="1">1</div>
<div sort="4">4</div>
<div sort="6">6</div>
<div sort="5">5</div>
</div>
Javascript (with jQuery):
var $wrapper = $('#wrapper');
$wrapper.find('div').sort(function (a, b) {
return +a.getAttribute('sort') - +b.getAttribute('sort');
})
.appendTo($wrapper);
Working demo.
In response to #Tim's comment, you can place the elements that do not have the sort attributes at the back of the wrapper element easily, even without jQuery.
Assuming that this is your HTML:
<div id="wrapper">
<div style="color:red;">red color, without sort attribute</div>
<div style="color:red;" sort="7">red color (sort attribute=7)</div>
<div sort="2">2</div>
<div sort="3">3</div>
<div sort="1">1</div>
<div sort="4">4</div>
<div sort="6">6</div>
<div sort="5">5</div>
</div>
You can place the element(s) that do not have the sort attribute by having this as your Javascript:
// As shown earlier above,
var $wrapper = $('#wrapper');
$wrapper.find('div').sort(function (a, b) {
return +a.getAttribute('sort') - +b.getAttribute('sort');
})
.appendTo($wrapper);
// New code to add:
var divs = document.getElementsByTagName('div');
for(var i = 0; i < divs.length; i++) {
if(divs[i].getAttribute('sort') == null || divs[i].getAttribute('sort') == undefined) {
divs[i].parentNode.appendChild(divs[i]);
}
}
Working demo.
clone it before using .tsort
$sort_order = $('div').clone().tsort({attr:'sort'});
DEMO

Is there a jQuery selector to accomplish this task?

I have these 4 HTML snippets:
Siblings:
<div class="a">...</div>
<div class="b">...</div> <!--selected-->
<div class="b">...</div> <!--not selected-->
Wrapped 1:
<div class="a">...</div>
<div>
<div class="b">...</div> <!--selected-->
</div>
<div class="b">...</div> <!--not selected-->
Wrapped 2:
<div>
<div class="a">...</div>
</div>
<div>
<div class="b">...</div> <!--selected-->
</div>
<div class="b">...</div> <!--not selected-->
Separated:
<div class="a">...</div>
<div>...</div>
<div class="b">...</div> <!--selected-->
<div>...</div>
<div class="b">...</div> <!--not selected-->
<div>...</div>
<div class="b">...</div> <!--not selected-->
How can I, with jQuery, select the next .b element for any given .a element, regardless of nesting?
I want something like this:
$('.a').each(function() {
var nearestB = $(this)./*Something epically wonderful here*/;
//do other stuff here
});
Can you try this to see if it suits your case?
$(document).ready(function () {
var isA = false;
$('div.a, div.b').each(function () {
if ($(this).attr('class') == "a")
isA = true;
if ($(this).attr('class') == "b" && isA) {
$(this).css("background", "yellow");
isA = false;
}
});
});
Regards...
Got it!
var both = $('.a, .b');
$('.a').each(function() {
var nearestB = both.slice(both.index(this))
.filter('.b')
.first();
//do stuff
});​
How are you deciding which .a to select? Is there a .b for ever .a? Are you looping over each? You could use the index of the .a and simply select the corresponding .b.
$(".a").each(function(){
var index = $(".a").index(this);
var theB = $(".b").get(index);
});
Ok, here's a modified version of Padel's solution, that behaves slightly differently
var lastA = null;
$('.a, .b').each(function() {
if($(this).hasClass('a'))
{
lastA = $(this);
}
else if(lastA)
{
doStuff(lastA,this); //doStuff(a,b)
lastA = null;
}
});
$("div.a").nextAll("div.b")
Does this work?

Categories

Resources