Apply CSS if text exceeds a certain length - javascript

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

Related

Checking if the values are greater than a certain number in cypress

I have this div and want to check if all the texts within this div are greater than 800. Is there any way to do this in cypress?
<div>
<div>700</div>
<div>720</div>
<div>810</div>
<div>830</div>
<div>850</div>
</div>
it("Show cars below 700 euro", () => {
var prices=cy.get("div > div >").should()
)}
First assign a className for your div, for example value1.
<div className="value1">700</div>
Then:
cy.get(".value1").invoke('text').then(parseFloat).should('be.gte', 800)
Assuming that doing cy.get("div > div") will return you only the elements you want to check, you can simply iterate over the yielded element list, using .each()
cy.get("div > div").each((el) => {
const text = el.text();
expect(text).to.be.greaterThan(800);
})
If the div > div does not uniquely yield only the elements you want to check, you will need to find a different way to uniquely isolate these elements. Adding a className, like Ali suggests, is one way.

jQuery count divs and add class after 20

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");
}
});
});

Need to get is any child inside an element is having a background

I need to find out is their any span having a style of background so I can get value from its attribute I have $(this). Structure is:
<div id="operative_time_limit" class="timedivd">
<span title="1 hours" data-y="1" data-x="0"></span>
<span title="2 hours" data-y="2" data-x="0"></span>
<span title="3 hours" data-y="3" data-x="0"></span>
<span title="4 hours" data-y="4" data-x="0"></span>
</div>
Using alert(jQuery(this).children().css('background').length); but always getting 0 as result
try this,
alert($('#operative_time_limit').find('span').length);
For span which has background-color property then try it like,
var c=0;
$('#operative_time_limit').find('span').each(function(){
if($(this).css('backgroundColor')) // or 'background-color'
c++;
});
alert(c);
I am not sure what exactly $(this) is in your context.
However the following:
var count = 0;
$('#operative_time_limit span').each(function(index){
if($(this).css('background')){
count++;
}
});
alert(count);
Will do it. Further extrapolating from your question to presume that you want to extract some attribute (lets call it someAttr), from the span with a background of css, and there is only one such span. Assuming those are correct assumptions, the following will give you what you want:
var attributeValue;
$('#operative_time_limit span').each(function(index){
if($(this).css('background')){
attributeValue = $(this).attr('someAttr');
}
});
You now have your desired value in attributeValue
The following line will give you the length of Children of $(this)
alert(jQuery(this).children().css('background').length);
You could use the following code to find all the span's that have background color other than white (assuming white is default color)
var length = $('#operative_time_limit').children().filter(function () {
return $(this).css('background-color') != 'rgba(0, 0, 0, 0)' && $(this).css('background-color') != 'transparent';
}).length;
here, variable length can be used to determine how many spans have background property
See working fiddle
use following
alert(jQuery(this).children().hasClass('background')).
hasClss determines whether any of the matched elements are assigned the given class.
The .hasClass() method will return true if the class is assigned to an element, even if other classes also are

jQuery, selecting just number from id like "article-23"

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

Need to add multiple elements to search for a particular class with jQuery

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
}

Categories

Resources