I have multiple elements in the dom with a class of .blockbadge if the value of any .block-badge is 0 then I want to add a class to that element in order to style it differently.
My JS adds the class to all of these elements if anyone of them equal 0. How do I make it only affect those elements which equal zero?
HTML
<span class="block-badge">1</span>
<span class="block-badge">0</span> // this element should have the class 'zero' added
<span class="block-badge">4</span>
JS
var blockBadgeVal = $('.block-badge').val();
if (blockBadgeVal < 0) {
$('.block-badge').addClass('zero');
}
The code in the OP will not work because $('.block-badge').html() will return the html of the first element with class block-badge so in this case return string 1, you should parse the returned value then compare it with the 0.
You could use filter() method instead.
Description: Reduce the set of matched elements to those that match the selector or pass the function's test.
$('.block-badge').filter(function(){
return parseInt($(this).text())==0;
}).addClass('zero');
Hope this helps.
$('.block-badge').filter(function(){
return parseInt($(this).text())==0;
}).addClass('zero');
.zero{
color: red;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="block-badge">1</span>
<span class="block-badge">0</span>
<span class="block-badge">4</span>
Like this
$('.block-badge').each(function(){
if(parseInt($(this).html()) ===0){
$(this).addClass('zero');
}
});
You could use the jQuery :contains selector for that specific markup
$('.block-badge:contains(0)').addClass('zero');
it won't work if any other elements contains a zero, like 10, 101 etc. so if you need only 0, use a filter
FIDDLE
Try using .text(function(index, originalText) {}) where this is current element within collection , originalHtml is current textContent
$(document).ready(function() {
$(".block-badge").text(function(index, originalText) {
if (originalText <= 0) {
$(this).addClass("zero");
}
return originalText
});
});
jsfiddle https://jsfiddle.net/s2g3zpwr/3/
I have below HTML
<div class="parent">
<span class="child">1</span>
<span class="child">2</span>
<span class="child">3</span>
<span class="child">4</span>
<span class="child">5</span>
</div>
and below CSS
.parent .child {
border : 1px solid black;
display :inline-block;
width:40px;
height:25px;
text-align:center;
cursor:pointer;
}
.mark {
background-color: green;
}
and simple click event for to see selected element a below.
$(".parent > .child").click(function(e){
if(e.shiftKey) {
$(".parent .child").each(function(){
$(this).addClass("mark");
});
}
else {
$(this).addClass("mark");
}
});
Edited : When I click one element and another element with shiftKey , between these two elements should be add class mark. But my code iterate all elements as $(".parent > .child").... I would like to avoid it (I mean if 2 elements between them , I would like to iterate 4 times (inclusive start and element) with my iteration).
My question is can I iterate between two selected elements (inclusive) instead of iterating from thier parent element (in my case I don't want to iterate from parent) ? I know the start and end elements. If so, why I need to iterate all elements and check their status as I want ? JSFiddle link.
For clear question ...
I have 10 HTML element ,assume 3 is start and 6 is end.I would like to iterate as
(for var i=3 ; i <=6 ; i++) {...}
instead of iterating all elements and check their status as
(for var i=1 ; i <=10 ; i++) {
// checking is it between start and end elements
}
Demo
Try this demo. Not sure if it accomplishes what you need. Comment if changes needed.
$(".parent .child").click(function () {
if($(".parent .child.mark:first").length == 1 && !$(this).hasClass('mark')){
firstIndex = $(".parent .child.mark:first").index();
thisIndex = $(this).index();
start = Math.min(thisIndex, firstIndex);
end = Math.max(firstIndex, thisIndex) + 1;
$('.parent .child').slice(start, end).each(function(){
$(this).addClass('mark');
})
} else {
$(this).addClass('mark');
}
});
Not clear from your question but are you saying something like this
Jquery for next element is :
$(".parent .child").click(function(){
$(this).addClass("mark");
$(this).next().addClass('mark');
if($(this).is(':last-child')){
$('.parent .child:first-child').addClass('mark');
}
});
If element is last child then have added class mark to first ,this one was my assumption so far.
Why don't you use this:
$( ".mark" ).nextUntil( ".mark" ).css( "color", "red" );
$( ".mark" )--> this is your first click item
.nextUntil( ".mark" )--> this one is your second click
Hope it will works
I have a pseudoelement :after content defined in CSS.
div:after {
content:'This is the sentence.';
}
Can anyone please advise me how to target the first character of the content and change its style. Jquery is OK but I'm trying to do it with first* pseudoelement.
The only time :first-letter could possibly match the first letter of an :after pseudo-element is if the pseudo-element is inline, and there is no other content preceding the pseudo-element (at least in the usual LTR writing mode anyway). Furthermore, pseudo-elements cannot contain their own pseudo-elements, so you couldn't do :after:first-letter either.
If your div element has content, then you won't be able to do this using an :after pseudo-element. You will need to use an actual child element instead. You can easily generate one using jQuery's .append() method, but if you want to target :first-letter of that element, you will need to display it as either block or inline-block instead of inline:
$('div').append('<span class="after">This is the sentence.</span>');
div > .after {
display: inline-block;
}
div > .after:first-letter {
color: red;
}
You won't be able to do anything like div::after::first-letter for the time being, but you can achieve the same end-results relatively easily by merely creating the content you wish to manipulate, and injecting it into your DOM where the div::after pseudo elements would have been placed had they been used:
(function () {
var aftr = document.createElement( "div" ),
divs = document.querySelectorAll( "div" );
aftr.className = "after";
aftr.textContent = "This is the sentence.";
for ( var i = 0; i < divs.length; i++ ) {
divs.item(i).appendChild( aftr.cloneNode( true ) );
}
}());
With these elements now in place, you can move on to styling them:
.after:last-child::first-letter {
color: red;
padding: .5em 1em;
border: 1px solid red;
}
Fiddle: http://jsfiddle.net/jonathansampson/7gmbvewh/
One thing that immediately makes me uncomfortable is the distance between the markup and the text you want displayed within these elements. You could place the text within the markup as a data attribute:
<div data-after="After content">Original Content</div>
And then use that (if it exists) in the final loop:
for ( var i = 0; i < divs.length; i++ ) {
var clone = aftr.cloneNode( true ),
after = divs.item(i).dataset.after;
if ( after ) {
clone.textContent = after;
}
divs.item(i).appendChild( clone );
}
Fiddle: http://jsfiddle.net/jonathansampson/7gmbvewh/2/
If this is a feature question, then the answer is:
Unfortunatelly you can't target and manipulate with pseudo-elements.
But there are workarounds (don't use :after, but actual elements), read the comments under your question.
I was wondering how I could use the element that I check with .has() using jQuery.
This is what I have so far
HTML
<div>
<!--Only this paragraph should have a red background -->
<p>This is a paragraph</p>
<h1>This is not a paragraph</h1>
</div>
<div>
<h1>This is not a paragraph</h1>
</div>
jQuery
$("div").has("p").addClass("para");
As you can see, I ask if my div has a <p> and if so to add a class. My intention was to add the class to the paragraph but it seem to be that the class is added to my division. How can I add the class to my <p> after using $("div").has("p")?
I should put it in an if statement like this
if($("div").has("p")){
{...}.addClass("para");
}
but how can I add the class to my <p>?
I have a fiddle to make it clear
(I know I could use .each() for this problem but I want to know if it's possible with .has() too?)
simply you can use
$("div p").addClass("para");
While I recommend that you follow Mr. Aliens suggestion, if you absolutely must use .has() you have to first select the paragraph. When you write it like this:
$("div").has("p").addClass("para");
Your selected element is still the div(s).
If you want to avoid writing an If-statement, write the check this way:
$("div").has("p").find("p").addClass("para");
EDIT: This doesn't really check IF the div contains a paragraph, but rather selects the ones that have. The result is basically the same.
if($("div").find("p").length != 0) {
// another way to check if there is a p element inside of a div
$("div").find("p").addClass("para");
}
OR if you are not happy with this you can change jQuery's has function to this
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length,
has = false;
this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
has = true;
}
}
});
return has;
},
$("div").has("p").find('p').addClass('class_name');
// It will add class on p if div has p element
How do I toggle the visibility of an element using .hide(), .show(), or .toggle()?
How do I test if an element is visible or hidden?
Since the question refers to a single element, this code might be more suitable:
// Checks CSS content for display:[none|block], ignores visibility:[true|false]
$(element).is(":visible");
// The same works with hidden
$(element).is(":hidden");
It is the same as twernt's suggestion, but applied to a single element; and it matches the algorithm recommended in the jQuery FAQ.
We use jQuery's is() to check the selected element with another element, selector or any jQuery object. This method traverses along the DOM elements to find a match, which satisfies the passed parameter. It will return true if there is a match, otherwise return false.
You can use the hidden selector:
// Matches all elements that are hidden
$('element:hidden')
And the visible selector:
// Matches all elements that are visible
$('element:visible')
if ( $(element).css('display') == 'none' || $(element).css("visibility") == "hidden"){
// 'element' is hidden
}
The above method does not consider the visibility of the parent. To consider the parent as well, you should use .is(":hidden") or .is(":visible").
For example,
<div id="div1" style="display:none">
<div id="div2" style="display:block">Div2</div>
</div>
The above method will consider div2 visible while :visible not. But the above might be useful in many cases, especially when you need to find if there is any error divs visible in the hidden parent because in such conditions :visible will not work.
None of these answers address what I understand to be the question, which is what I was searching for, "How do I handle items that have visibility: hidden?". Neither :visible nor :hidden will handle this, as they are both looking for display per the documentation. As far as I could determine, there is no selector to handle CSS visibility. Here is how I resolved it (standard jQuery selectors, there may be a more condensed syntax):
$(".item").each(function() {
if ($(this).css("visibility") == "hidden") {
// handle non visible state
} else {
// handle visible state
}
});
From How do I determine the state of a toggled element?
You can determine whether an element is collapsed or not by using the :visible and :hidden selectors.
var isVisible = $('#myDiv').is(':visible');
var isHidden = $('#myDiv').is(':hidden');
If you're simply acting on an element based on its visibility, you can just include :visible or :hidden in the selector expression. For example:
$('#myDiv:visible').animate({left: '+=200px'}, 'slow');
Often when checking if something is visible or not, you are going to go right ahead immediately and do something else with it. jQuery chaining makes this easy.
So if you have a selector and you want to perform some action on it only if is visible or hidden, you can use filter(":visible") or filter(":hidden") followed by chaining it with the action you want to take.
So instead of an if statement, like this:
if ($('#btnUpdate').is(":visible"))
{
$('#btnUpdate').animate({ width: "toggle" }); // Hide button
}
Or more efficient, but even uglier:
var button = $('#btnUpdate');
if (button.is(":visible"))
{
button.animate({ width: "toggle" }); // Hide button
}
You can do it all in one line:
$('#btnUpdate').filter(":visible").animate({ width: "toggle" });
The :visible selector according to the jQuery documentation:
They have a CSS display value of none.
They are form elements with type="hidden".
Their width and height are explicitly set to 0.
An ancestor element is hidden, so the element is not shown on the page.
Elements with visibility: hidden or opacity: 0 are considered to be visible, since they still consume space in the layout.
This is useful in some cases and useless in others, because if you want to check if the element is visible (display != none), ignoring the parents visibility, you will find that doing .css("display") == 'none' is not only faster, but will also return the visibility check correctly.
If you want to check visibility instead of display, you should use: .css("visibility") == "hidden".
Also take into consideration the additional jQuery notes:
Because :visible is a jQuery extension and not part of the CSS specification, queries using :visible cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :visible to select elements, first select the elements using a pure CSS selector, then use .filter(":visible").
Also, if you are concerned about performance, you should check Now you see me… show/hide performance (2010-05-04). And use other methods to show and hide elements.
How element visibility and jQuery works;
An element could be hidden with display:none, visibility:hidden or opacity:0. The difference between those methods:
display:none hides the element, and it does not take up any space;
visibility:hidden hides the element, but it still takes up space in the layout;
opacity:0 hides the element as "visibility:hidden", and it still takes up space in the layout; the only difference is that opacity lets one to make an element partly transparent;
if ($('.target').is(':hidden')) {
$('.target').show();
} else {
$('.target').hide();
}
if ($('.target').is(':visible')) {
$('.target').hide();
} else {
$('.target').show();
}
if ($('.target-visibility').css('visibility') == 'hidden') {
$('.target-visibility').css({
visibility: "visible",
display: ""
});
} else {
$('.target-visibility').css({
visibility: "hidden",
display: ""
});
}
if ($('.target-visibility').css('opacity') == "0") {
$('.target-visibility').css({
opacity: "1",
display: ""
});
} else {
$('.target-visibility').css({
opacity: "0",
display: ""
});
}
Useful jQuery toggle methods:
$('.click').click(function() {
$('.target').toggle();
});
$('.click').click(function() {
$('.target').slideToggle();
});
$('.click').click(function() {
$('.target').fadeToggle();
});
This works for me, and I am using show() and hide() to make my div hidden/visible:
if( $(this).css('display') == 'none' ){
/* your code goes here */
} else {
/* alternate logic */
}
You can also do this using plain JavaScript:
function isRendered(domObj) {
if ((domObj.nodeType != 1) || (domObj == document.body)) {
return true;
}
if (domObj.currentStyle && domObj.currentStyle["display"] != "none" && domObj.currentStyle["visibility"] != "hidden") {
return isRendered(domObj.parentNode);
} else if (window.getComputedStyle) {
var cs = document.defaultView.getComputedStyle(domObj, null);
if (cs.getPropertyValue("display") != "none" && cs.getPropertyValue("visibility") != "hidden") {
return isRendered(domObj.parentNode);
}
}
return false;
}
Notes:
Works everywhere
Works for nested elements
Works for CSS and inline styles
Doesn't require a framework
I would use CSS class .hide { display: none!important; }.
For hiding/showing, I call .addClass("hide")/.removeClass("hide"). For checking visibility, I use .hasClass("hide").
It's a simple and clear way to check/hide/show elements, if you don't plan to use .toggle() or .animate() methods.
Demo Link
$('#clickme').click(function() {
$('#book').toggle('slow', function() {
// Animation complete.
alert($('#book').is(":visible")); //<--- TRUE if Visible False if Hidden
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clickme">
Click here
</div>
<img id="book" src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png" alt="" width="300"/>
Source (from my blog):
Blogger Plug n Play - jQuery Tools and Widgets: How to See if Element is hidden or Visible Using jQuery
ebdiv should be set to style="display:none;". It works for both show and hide:
$(document).ready(function(){
$("#eb").click(function(){
$("#ebdiv").toggle();
});
});
One can simply use the hidden or visible attribute, like:
$('element:hidden')
$('element:visible')
Or you can simplify the same with is as follows.
$(element).is(":visible")
Another answer you should put into consideration is if you are hiding an element, you should use jQuery, but instead of actually hiding it, you remove the whole element, but you copy its HTML content and the tag itself into a jQuery variable, and then all you need to do is test if there is such a tag on the screen, using the normal if (!$('#thetagname').length).
When testing an element against :hidden selector in jQuery it should be considered that an absolute positioned element may be recognized as hidden although their child elements are visible.
This seems somewhat counter-intuitive in the first place – though having a closer look at the jQuery documentation gives the relevant information:
Elements can be considered hidden for several reasons: [...] Their width and height are explicitly set to 0. [...]
So this actually makes sense in regards to the box-model and the computed style for the element. Even if width and height are not set explicitly to 0 they may be set implicitly.
Have a look at the following example:
console.log($('.foo').is(':hidden')); // true
console.log($('.bar').is(':hidden')); // false
.foo {
position: absolute;
left: 10px;
top: 10px;
background: #ff0000;
}
.bar {
position: absolute;
left: 10px;
top: 10px;
width: 20px;
height: 20px;
background: #0000ff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">
<div class="bar"></div>
</div>
Update for jQuery 3.x:
With jQuery 3 the described behavior will change! Elements will be considered visible if they have any layout boxes, including those of zero width and/or height.
JSFiddle with jQuery 3.0.0-alpha1:
http://jsfiddle.net/pM2q3/7/
The same JavaScript code will then have this output:
console.log($('.foo').is(':hidden')); // false
console.log($('.bar').is(':hidden')); // false
expect($("#message_div").css("display")).toBe("none");
$(document).ready(function() {
if ($("#checkme:hidden").length) {
console.log('Hidden');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="checkme" class="product" style="display:none">
<span class="itemlist"><!-- Shows Results for Fish --></span> Category:Fish
<br>Product: Salmon Atlantic
<br>Specie: Salmo salar
<br>Form: Steaks
</div>
To check if it is not visible I use !:
if ( !$('#book').is(':visible')) {
alert('#book is not visible')
}
Or the following is also the sam, saving the jQuery selector in a variable to have better performance when you need it multiple times:
var $book = $('#book')
if(!$book.is(':visible')) {
alert('#book is not visible')
}
Use class toggling, not style editing . . .
Using classes designated for "hiding" elements is easy and also one of the most efficient methods. Toggling a class 'hidden' with a Display style of 'none' will perform faster than editing that style directly. I explained some of this pretty thoroughly in Stack Overflow question Turning two elements visible/hidden in the same div.
JavaScript Best Practices and Optimization
Here is a truly enlightening video of a Google Tech Talk by Google front-end engineer Nicholas Zakas:
Speed Up Your Javascript (YouTube)
After all, none of examples suits me, so I wrote my own.
Tests (no support of Internet Explorer filter:alpha):
a) Check if the document is not hidden
b) Check if an element has zero width / height / opacity or display:none / visibility:hidden in inline styles
c) Check if the center (also because it is faster than testing every pixel / corner) of element is not hidden by other element (and all ancestors, example: overflow:hidden / scroll / one element over another) or screen edges
d) Check if an element has zero width / height / opacity or display:none / visibility:hidden in computed styles (among all ancestors)
Tested on
Android 4.4 (Native browser/Chrome/Firefox), Firefox (Windows/Mac), Chrome (Windows/Mac), Opera (Windows Presto/Mac WebKit), Internet Explorer (Internet Explorer 5-11 document modes + Internet Explorer 8 on a virtual machine), and Safari (Windows/Mac/iOS).
var is_visible = (function () {
var x = window.pageXOffset ? window.pageXOffset + window.innerWidth - 1 : 0,
y = window.pageYOffset ? window.pageYOffset + window.innerHeight - 1 : 0,
relative = !!((!x && !y) || !document.elementFromPoint(x, y));
function inside(child, parent) {
while(child){
if (child === parent) return true;
child = child.parentNode;
}
return false;
};
return function (elem) {
if (
document.hidden ||
elem.offsetWidth==0 ||
elem.offsetHeight==0 ||
elem.style.visibility=='hidden' ||
elem.style.display=='none' ||
elem.style.opacity===0
) return false;
var rect = elem.getBoundingClientRect();
if (relative) {
if (!inside(document.elementFromPoint(rect.left + elem.offsetWidth/2, rect.top + elem.offsetHeight/2),elem)) return false;
} else if (
!inside(document.elementFromPoint(rect.left + elem.offsetWidth/2 + window.pageXOffset, rect.top + elem.offsetHeight/2 + window.pageYOffset), elem) ||
(
rect.top + elem.offsetHeight/2 < 0 ||
rect.left + elem.offsetWidth/2 < 0 ||
rect.bottom - elem.offsetHeight/2 > (window.innerHeight || document.documentElement.clientHeight) ||
rect.right - elem.offsetWidth/2 > (window.innerWidth || document.documentElement.clientWidth)
)
) return false;
if (window.getComputedStyle || elem.currentStyle) {
var el = elem,
comp = null;
while (el) {
if (el === document) {break;} else if(!el.parentNode) return false;
comp = window.getComputedStyle ? window.getComputedStyle(el, null) : el.currentStyle;
if (comp && (comp.visibility=='hidden' || comp.display == 'none' || (typeof comp.opacity !=='undefined' && comp.opacity != 1))) return false;
el = el.parentNode;
}
}
return true;
}
})();
How to use:
is_visible(elem) // boolean
Example of using the visible check for adblocker is activated:
$(document).ready(function(){
if(!$("#ablockercheck").is(":visible"))
$("#ablockermsg").text("Please disable adblocker.").show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ad-placement" id="ablockercheck"></div>
<div id="ablockermsg" style="display: none"></div>
"ablockercheck" is a ID which adblocker blocks. So checking it if it is visible you are able to detect if adblocker is turned On.
$(document).ready(function() {
var visible = $('#tElement').is(':visible');
if(visible) {
alert("visible");
// Code
}
else
{
alert("hidden");
}
});
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<input type="text" id="tElement" style="display:block;">Firstname</input>
You need to check both... Display as well as visibility:
if ($(this).css("display") == "none" || $(this).css("visibility") == "hidden") {
// The element is not visible
} else {
// The element is visible
}
If we check for $(this).is(":visible"), jQuery checks for both the things automatically.
Simply check visibility by checking for a boolean value, like:
if (this.hidden === false) {
// Your code
}
I used this code for each function. Otherwise you can use is(':visible') for checking the visibility of an element.
Because Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout (as described for jQuery :visible Selector) - we can check if element is really visible in this way:
function isElementReallyHidden (el) {
return $(el).is(":hidden") || $(el).css("visibility") == "hidden" || $(el).css('opacity') == 0;
}
var booElementReallyShowed = !isElementReallyHidden(someEl);
$(someEl).parents().each(function () {
if (isElementReallyHidden(this)) {
booElementReallyShowed = false;
}
});
But what if the element's CSS is like the following?
.element{
position: absolute;left:-9999;
}
So this answer to Stack Overflow question How to check if an element is off-screen should also be considered.
A function can be created in order to check for visibility/display attributes in order to gauge whether the element is shown in the UI or not.
function checkUIElementVisible(element) {
return ((element.css('display') !== 'none') && (element.css('visibility') !== 'hidden'));
}
Working Fiddle
Also here's a ternary conditional expression to check the state of the element and then to toggle it:
$('someElement').on('click', function(){ $('elementToToggle').is(':visible') ? $('elementToToggle').hide('slow') : $('elementToToggle').show('slow'); });
if($('#postcode_div').is(':visible')) {
if($('#postcode_text').val()=='') {
$('#spanPost').text('\u00a0');
} else {
$('#spanPost').text($('#postcode_text').val());
}