Opposite of not() function - javascript

I have a simple question, I've the following lines which equals to not active links:
$links.not($active).each(function()
{
//Do sth...
});
what is the opposite of the .not(...) function in JavaScript? because I need to know the active links, Any ideas !?

This is jQuery, not JavaScript. The opposite of .not is .filter.

Using $links.not($active) creates a collection with the elements from $links except the elements in $active.
To get the active links, just use the $active object:
$active.each(function()
{
//Do sth...
});

You're looking for .filter(), which returns a subset that only includes matching elements.

The opposite of not in programming is often named is
http://api.jquery.com/is/
However this will return boolean true of false so in your case you'll be wanting filter
http://api.jquery.com/filter/
Example:
$links.filter('.onlyThisClass').each(function()
{
//Do sth...
});

Related

How do I check if an element is NOT empty with jquery?

I need to check if an element is empty and if another is NOT empty. The first part of the if works but how do I check if the #dynamicForm element is NOT empty?ยจ
This obviously doesn't work but I need something like it:
if ($("#formButton").is(':empty') && $("#dynamicForm").is(':notempty')) {
//do stuff
}
if(!$("#dynamicForm").is(':empty')){
// code here...
}
Note the not operator (!) in front.
First of all you can check if the selected element is empty and negate it:
!$('#dynamicForm').is(':empty')
Furthermore you can check if it's not empty with jquery selector :not:
$('#dynamicForm').is(':not(:empty)')
A third way would be to select all elements, that are not empty and check the length of the jquery collection:
$('#dynamicForm').not(':empty').length
If you need this check in several places you can add your own function to jQuery:
$.fn.notEmpty = function() {
return !$(this).is(':empty')
}
you can use it like this:
if($('#dynamicForm').notEmpty())
That isn't realy clean and it's not keeping with the jquery conventions. So better extend the selectors instead of extending the functions:
$.extend($.expr[':'],{
notEmpty:function(c) {
return !$(c).is(':empty');
}
});
Now you can use it very straightforward:
if($('#dynamicForm').is(':notEmpty'))

Remove element depending on it's background-image

I'm trying to remove an element from a page based on it's background attribute.
Something like:
if ( $('td').attr('background','backgroundimageurl')){this.remove();}
But this does not work any suggestions?
You can also use filter to filter the result set based on your operations:
$( 'td' ).filter( function(){
// return true of it matches, thus, keeping it in the object
return $(this).css( 'backgroundImage' ) === 'someUrlOrWhatever';
}).remove();
Demo per roXon's request: http://jsfiddle.net/danheberden/9rTZj/
However, it would be better to do a check like
return /someDomain\.com\/path\/to\/whatever/.test( $( this ).css( 'backgroundImage' ) );
in the filter function. Different browsers will return different formatting for css rules, as roXon pointed out about the === approach won't work in FF because the returned string will be url("thePath") instead of url(thePath) like in webkit. Thus, just testing for the url value would be most flexible.
The reason it's not working is that in your code snippet, "this" is the current context (most likely the window).
This might do what you want:
$('td').each(function (i, e) {
if (e.style.foo === "bar") {
$(e).remove();
}
});
each iterates through all of the elements that matched. i is the number of the loop, and e is the current element. So we test each element and then act when we find the one with the style we want.
Even shorter example:
$('td[background="backgroundimageurl"]').remove();
Do some reading on jQuery selectors. They can be really useful :)
http://api.jquery.com/category/selectors/
Try this. When you were doing attr("background","backgroundurl") this was trying to set the background attr rather than find elements matching. This will do the trick.
if($("body").find("td").css("background-image") == "backgroundimageurl"){this.detach()};

Combining to elements for a focus function

How would I combine two elements to use the focus function? #s_type and #s_ctry I'm trying to avoid extra code by retyping the same exact thing twice.
the way i'm trying it now doesn't work.
<script type="text/javascript">
$(document).ready(function() {
$("#s_type", "#s_ctry").focus(function() {
var first = $(this).find("option").eq(0);
if(first.val() === "0") {
first.remove();
}
});
});
</script>
You have to use a comma in the selector itself:
$("#s_type, #s_ctry")
Reference
You were nearly there! You need to combine them into one string. When you pass 2 arguments to jQuery, the second one is a context in which to match the selector, you can't provide multiple selectors as separate arguments:
$("#s_type, #s_ctry").focus(function() {
//Do stuff!
});
Alternatively, you can use the add method to add elements to the matched set:
$("#s_type").add("#s_ctry").focus(function() {
//Do stuff!
});

How do I use hasClass to detect if a class is NOT the class I want?

How do I use hasClass so it works as doesNotHaveClass? In other words, rather than looking to see if it is a specified class, looking to see if it is NOT a specified class. Can I use an exclamation point or something like that?
Yes, you can.
if (!$('element').hasClass('do-not-want')) {
// This element does not have the .do-not-want class
}
However if you're trying to use selectors to find all the items that don't have a class, perhaps try this:
// find all divs that don't have "badClass" class
$('div').not('.badClass').each(function(){});
if (!$('a').hasClass('xyz')){
...
}
Yes, you can
As per the jQuery documentation:
The .hasClass() method will return true if the class is assigned to an element, even if other classes also are.
Since the function returns a boolean you can use exclamation point to negate the result.
You can check if the return is false:
if($(element).hasClass("class") === false) {...}

How can I tell whether an element matches a selector?

Let's say I've got a DOM element - how can I tell whether it matches a jQuery selector, such as p or .myclass? It's easy to use the selector to match children of the element, but I want a true/false answer to whether this particular element match?
The element may not have an ID (and I can't assign it a random one for reasons beyond this), so I can't apply my selector to the element's parent and look for children with the same ID as mine.
Will this work as intended? I can't figure out Javascript object comparisons.
$(selector, myElement.parentNode).each({
if (this == myElement) // Found it
});
Seems like there would be an easy way to see whether a DOM element matches a jQuery selector...
You can use the is() method:
if($(this).is("p")){
// ...
}
Without jQuery, using Element.matches():
var elements = document.querySelectorAll('div');
console.log(
elements[0].matches('.foo'), // true
elements[0].matches('.bar'), // false
elements[1].matches('[title=bar]'), // true
)
<div class='foo'></div>
<div title='bar'></div>
See supported browsers list
I believe the is() method is what you are looking for.
Otherwise, you might just try selecting the item directly, if that is what you mean.
So if it's an "a" with a class of "myclass", just do $("a.myclass")
I can't apply my selector to the
element's parent and look for children
with the same ID as mine.
You can't do that anyway - the id attribute must be unique.
Maybe you just want:
$(".complicated #selector p.with > div.manyParts").length
If there are no matches, length returns 0, which is falsy, so you can use it in an if statement, like:
if($(".doesThis #exist").length) {
// Do things
}
Probably would be worth storing it in a separate variable and THEN checking the length; that way, if you need to do anything with the matched elements, you don't have to execute the same selector again.
Try Element.matches()
Element.matches()
document.addEventListener("click", event => {
if (event.target.matches(".elementsClass")) {
// It matches
} else {
// Does not match
}
});

Categories