I am using jQuery to count divs and would like to have a class added once it counts 20.
ie: divs 1-20 are class="box" and divs 21 + are class="box new"
This is what I have but it adds the "new" class to all the divs.
$(function() {
var divCount = $("#content").children(".box").length;
if (divCount > 20) {
$(".box").addClass("new");
}
});
$(".box:gt(20)").addClass("new");
Just want to point out that you can do this with just CSS using nth-child. Of course, if you're using the class for targeting you still may want to go the jQuery route:
div.box:nth-child(n+21) {
... new styles go here
}
See more here: http://css-tricks.com/useful-nth-child-recipies/
Something like this should work:
var i = 0;
$("#content").children(".box").each(function(i, k) {
if(++i > 20) $(k).addClass("new");
});
or
$("#content").children(".box").each(function(i, k) {
if($(k).is(":gt(20)")) $(k).addClass("new");
});
Take into account that your code says as follows:
If there are more than 20 boxes, add class 'new' to all the divs with class 'box'. And so, all the boxes are selected.
In this case, I recommed using the :gt() selector: gt-selector - jQuery
Therefore:
$(function() {
$(".box:gt(20)").addClass("new");
});
You can use this cheatsheet if you're not sure which selector to use: Oscar Otero jQuery Cheatsheet
Your code:
if (divCount > 20)
is actually checking a condition for truthfulness and adding a class "new" to all elements that have the class .box because the condition passes the test when you have more than 20 divs.
What you want to do is loop through the elements and check for truthfulness of your condition inside that, applying the new class to the current element if it's index is above 20 - 1 (counting starts at zero, so your element with an index of 19 will be your 20th element).
$(function() {
$.each($("#content").children(".box"), function(index, value){
if ( index - 1 > 20 ) {
$(this).addClass(".new");
}
});
});
Related
Is there a way to apply a CSS to an element if the text within the element exceeds a certain length. For instance <p class="foo">123456789</p>.
Then, when the text within the element exceeds x characters a new class is applied
<p class="foo text-exceeds-X-chars">12345678910101010101</p>
I'd suggest using the addClass callback function:
$('p.foo').addClass(function() {
return $.trim(this.textContent).length > 10
? 'text-exceeds-X-chars'
: null;
});
Use jQuery text(), then, use length. If the condition is fulfilled, use addClass() to apply the class
if($('p.foo').text().length > 20){
$('p.foo').addClass('my-class');
}
If you have multiple p.foo elements, do
$('p.foo').each(function(){
if($(this).text().length > 20){
$(this).addClass('my-class');
}
});
There is not built-in filter or selector for this, so you will have to do it manually. The idea is to select all elements in question and test the length of each of them in loop:
$('.foo').each(function() {
if ($(this).text().length > x) {
$(this).addClass('text-exceeds-X-chars');
}
});
I'm in a situation where I want to check if two elements (one is clicked and another one a reference) are the same, what I'm trying to do is:
$("#process li").click(function() {
currentElement = $(this);
referenceElement = $("#process li:first-child");
if (currentElement === referenceElement) {
$(".mark").removeClass("mark");
$(this).addClass("mark");
}
});
So what I want is to check if the clicked <li> is the first child of the ul#process and if so first remove a .mark class from another element and then add it to the clicked one. I don't get any working result - ideas anyone?
UPDATE:
Thanks you very much! This is my solution:
$("#processlist li").click(function() {
currentElement = $(this);
if (currentElement.is('li:first-child')) {
$(this).addClass("mark");
}
});
Now if I click on a , if it is the first child of this list, the class .mark is added - sweet!
Comparing objects in JS is very troublesome. The simplest way is to just pick a few key properties and compare those, eg:
if (currentElement.prop('id') === referenceElement.prop('id') {
// rest of your code...
}
However, given your use case you could use is:
if (currentElement.is('#process li:first-child')) {
// rest of your code...
}
Example fiddle
You need to extract the DOM element from the jQuery object. You can use the get method of jQuery for this.
e.g. if( currentElement.get( 0 ) === referenceElement.get( 0 ) )
All right, I have a div tag which got a class="blog-post" and id like id="article-23" (where "23" could be any number, as it is id of blog post in a database). I need to somehow get just a number from that id and than apply some rules to that div tag. So say:
if number from id % 2 == 0 {
set text colour black to associated div tag with class of blog-post
} else {
set text colour white to associated div tag with class of blog-post
}
Thats just a "pseudo" code to show logic that I wan't to apply dependent if number from id is even or odd, but the question remains same, how do I just get number from id like "article-23" ?
As simple as
var number = "article-23".match(/\d+/)[0];
But you have to be sure that any digit exists in the string, otherwise you'd get a error.
You can actually apply rules via function, which makes this the cleanest solution (in my opinion):
$(".blog-post").css('color', function () {
return +this.id.replace('article-', '') % 2 ? 'blue' : 'red';
});
http://jsfiddle.net/ExplosionPIlls/Jrc5u/
Try this:
$('.blog-post[id^="article-"]').each(function () {
if (parseInt(this.id.replace('article-', '')) % 2 === 0) {
$('#' + this.id).css('color', 'black');
} else {
$('#' + this.id).css('color', 'white');
}
});
jsFiddle Demo
As an alternative, HTML5 supports these things called "data attributes", which are specifically meant for attaching data to your DOM without abusing things like the "class" or "id" attributes. jQuery provides a handy .data method for reading these attributes in a more obvious way.
You can add your own numeric ID attribute using something like "data-id":
<div class="blog-post" data-id="23" />
$("#blog-post").each(function () {
console.log($(this).data("id")); // Look up the data-id attribute
});
If I'm understanding correctly, you want the number after the hyphen of the id tag of your .blog-post class.
var article = $(".blog-post").attr('id'); //get the id
var article = article.split("-"); // split it on hyphens
return article = article[article.length-1]; // return the last element
I am using jQuery and am currently looking in one type of element for a particular class. I need to update it to look in three different elements, but am not sure how to do this since I assume I will need to use an array?
Here's my current code:
$findRed = $("p.red", "#main");
if ( $findRed.length >= 1 ) {
greater or equal to one
}
I need to change it so it will look for .red in either a p, div, or span tag.
Any help would be appreciate.
Your selector can simply be .red. That will match any element type with that class. Or if you just want those specific elements, your selector could look like this:
$findRed = $("p.red, div.red, span.red", "#main");
var $findRd = $(":has(.red)", $("p, div, span", $("#main")));
try this:
$findRed = $("p.red", $("#main, #main2, #main3"));
//will look in main, main2 and main3
if ( $findRed.length >= 1 ) {
greater or equal to one
}
if ($("p > .red, div > .red, span > .red").length > 0){
// do something here
}
I'm currently using this to get the class for a specific bit of HTML on the page:
$(this).parent("div").attr('class')
But that div has multiple classes: current_status status_billed
My end goal here is to grab the class that starts with status_ and replace it with a different class name.
So using my .parent() function above, I'm able to select the div I need, but I then need to remove the status_billed class and replace it with, for example, status_completed (or a number of other class names).
Select divs that have the status_billed class:
$(this).parent('div.status_billed')
Select divs whose class attribute contains status_:
$(this).parent('div[class*=status_]')
That's about the best you'll get with jQuery selectors. You can do better using .filter():
$(this).parent('div').filter(function ()
{
var classes = $(this).attr('class').split(' ');
for (var i=0; i<classes.length; i++)
{
if (classes[i].slice(0,7) === 'status_')
{
return true;
}
}
return false;
});
...but I'm not sure why you're doing all this - .parent() returns at most 1 element. Did you mean .closest() or .parents()?