I have a list of div elements with a data-windows attribute:
I basically want to check if any of these are not hidden (and doing something if they are all hidden)
I'm looping through them like so, this works but I'm wondering if there's a more efficient way:
$("[data-windows]").each(function () {
if (!$(this).hasClass('hidden')) {
isSomethingShown = true;
return false;
}
});
You can use :visible pseudo selector :
if($("[data-windows]:visible").length){
//Atleast 1 is visible
}else{
//All hiden
}
or
var isSomethingShown = !!$("[data-windows]:visible").length; // Bang!Bang! [!!] convert into a boolean
Of course, if you want to explicitly check the class, both selector can be change to (and maybe should be for faster performance) $("[data-windows].hidden")
how bout this oneliner:
return $("[data-windows].hidden").length == 0 ? false : true;
Related
I'd like to select an element using javascript/jquery in Tampermonkey.
The class name and the tag of the elements are changing each time the page loads.
So I'd have to use some form of regex, but cant figure out how to do it.
This is how the html looks like:
<ivodo class="ivodo" ... </ivodo>
<ivodo class="ivodo" ... </ivodo>
<ivodo class="ivodo" ... </ivodo>
The tag always is the same as the classname.
It's always a 4/5 letter random "code"
I'm guessing it would be something like this:
$('[/^[a-z]{4,5}/}')
Could anyone please help me to get the right regexp?
You can't use regexp in selectors. You can pick some container and select its all elements and then filter them based on their class names. This probably won't be super fast, though.
I made a demo for you:
https://codepen.io/anon/pen/RZXdrL?editors=1010
html:
<div class="container">
<abc class="abc">abc</abc>
<abdef class="abdef">abdef</abdef>
<hdusf class="hdusf">hdusf</hdusf>
<ueff class="ueff">ueff</ueff>
<asdas class="asdas">asdas</asdas>
<asfg class="asfg">asfg</asfg>
<aasdasdbc class="aasdasdbc">aasdasdbc</aasdasdbc>
</div>
js (with jQuery):
const $elements = $('.container *').filter((index, element) => {
return (element.className.length === 5);
});
$elements.css('color', 'red');
The simplest way to do this would be to select those dynamic elements based on a fixed parent, for example:
$('#parent > *').each(function() {
// your logic here...
})
If the rules by which these tags are constructed are reliably as you state in the question, then you could select all elements then filter out those which are not of interest, for example :
var $elements = $('*').filter(function() {
return this.className.length === 5 && this.className.toUpperCase() === this.tagName.toUpperCase();
});
DEMO
Of course, you may want initially to select only the elements in some container(s). If so then replace '*' with a more specific selector :
var $elements = $('someSelector *').filter(function() {
return this.className.length === 5 && this.className.toUpperCase() === this.tagName.toUpperCase();
});
You can do this in vanilla JS
DEMO
Check the demo dev tools console
<body>
<things class="things">things</things>
<div class="stuff">this is not the DOM element you're looking for</div>
</body>
JS
// Grab the body children
var bodyChildren = document.getElementsByTagName("body")[0].children;
// Convert children to an array and filter out everything but the targets
var targets = [].filter.call(bodyChildren, function(el) {
var tagName = el.tagName.toLowerCase();
var classlistVal = el.classList.value.toLowerCase();
if (tagName === classlistVal) { return el; }
});
targets.forEach(function(el) {
// Do stuff
console.log(el)
})
I am able to hide an element on the page in this way
$('.info_player > .item_focus').hide();
I need to set a variable on true or false if the element .info_player has the class .item_focus applied or not.
How to make it with jquery?
Please provide me a sample of code
var hasClassItemFocus = $('.info_player > .item_focus').length > 0;
hasClassItemFocus will be true if .info_player has .item_focus as a class.
You describe different things in your code and description:
$('.info_player > .item_focus').hide();
means you have the elements like the below
...
<div class="info_player">
<div class="item_focus">
...
"if the element .info_player has the class .item_focus applied or not"
means the following:
div class="info_player item_focus"
For the latter case you can use hasClass method.
In the former case you can use $('.info_player > .item_focus').length or $('.info_player').find('.item_focus').length and more. Jquery provides multiple ways to do the same things.
you can use jquery .hasClass()
if($('.info_player').hasClass('item_focus'))
{
var a = value;
}
or by one line
var a = $('.info_player').hasClass('item_focus') ? "a" : "b";
I am trying to run a function that executes if a div only contains inline elements
I am not sure how to go about this short of having to list out every single block element and checking that the div doesn't contain that.
$(this).children().each(function(){
if(this.nodeName.toLowerCase() == 'p' || this.nodeName.toLowerCase() == 'h1' etc...){
check = true; //it contains block element so it is not only inline elements
return false;
}
});
Is there a better way?
Edit
To help clarify, I have a content editable div and the problem is that the user can delete all the block elements out of the div. I need to check this and add a block element to the div.
Check to see if those elements are actually block-level, as CSS can change their behavior completely:
var has_inline = $('#parent').children().filter(function() {
return $(this).css('display') !== 'block';
}).length > 0;
I'm not sure what you consider inline-block to be, so I'll just assume it behaves like an inline element for your purposes.
Demo: http://jsfiddle.net/hXckq/2/
How about has() in jQuery:
if ($(this).has("p,h1, ...")) { ... }
You could put the inline elements into a hash, then use in or hasOwnProperty:
var inline = {
"span": true,
"a": true,
...
};
if(this.nodeName.toLowerCase() in inline) {
}
Maybe try this, check if the css property of each element is indeed inline, this should work though I did not test this syntax may be incorrect:
$(this).children().each(function(){
if($(this).css('display', 'inline') == true){
return true;
}else{
return false;
}
}
I'm new to jQuery, familiar with PHP & CSS. I have nested, dynamically generated div's which I wish to send (the id's) to a server-side script to update numbers for. I want to check everything in the .content class. Only div's with id's should be sent for processing; however I'm having trouble making a recursive children() check...this is the best (non-recursively) I could do:
$(".content").children().each(function() {
if ($(this).attr('id').length == 0) {
$(this).children().each(function() {
if ($(this).attr('id').length == 0) {
$(this).children().each(function() {
if ($(this).attr('id').length == 0) {
$(this).children().each(function() {
alert($(this).attr('id'));
});
}
});
}
});
}
});
and it just alert()'s the id's of everything at the level where they should be. There must be a better way to do this...thank you in advance for any advice.
-Justin
Try:
var ids = $('.content div[id]').map(function() {
return this.id;
}).get();
.content div[id] will select you all div descendants (at any level) of .content with non-empty ID attributes. The [id] part is an example of the Has Attribute selector.
I have used .map. to extract the IDs of the matches, and .get() to convert the resulting object into a basic array.
Try it here: http://jsfiddle.net/M96yK/
You can do:
$(".content div[id]");
This will return a jQuery object that contains all div's which have id's specified
Is there a way to me do this?
<img id="example" src="anything.jpg" title="something" class="abc" />
$('.abc').each(function(){
//test if this result is something
if( $(this)...(???)...('[src^=anything]')) == 'anything.jpg'){
}
//another Jquery selector test for this one
if( $(this)...(???)...('#example').size() > 0){
}
});
This is just an example, what I need is pretty more complex.. But I would like to know if there is a way to make other jQuery selector test in the result of a first selector.. since "find" will find the children of $(this).. and .parent() get alot of brothers..
See what I mean?
Do you have any idea?
So sorry.. let me try again..
$('div').each();
get all "div", right?
But now in that function I need to make another "test" check if div class is "red" or "blue"..
See?
I need to test something else of the result based in Jquery selector..
I know I could do:
class = $(this).attr('class'); and then if(class=="blue"){} .. But I would like to do $('this[class=blue]').size()>0){}
The jQuery is() filter operates on a found set to detect if something is true or not.
The jQuery filter() method will further pare down a found set based on criteria.
var allDivs = $('div');
var greenOnes = allDivs.filter('.green');
var redOnes = allDivs.filter('.red' );
I think you need the is method:
$('.abc').each(function() {
$(this).is('[src^=anything]')
});
This is fairly simple though, but I can't really tell what you are trying to do by the description. Maybe this is enough to get you started though.
You can use the filter and is methods to filter/search within a jQuery object.
if( $(this).is('[src^="anything"]') ) {
}
elseif( $("#example").size() > 0) {
}
You could put $("#example") in a variable outside of the loop and then reference it inside the loop as well.
if(this.src.indexOf("anything") === 0) {
// source starts with 'anything'
}
if($("#example").length) {
// since there can be only one #example
// in a *valid* document
}
Based on your edit:
if($(this).hasClass("blue")) {
...
}
?