Compare 'e.target' to a jQuery object - javascript

What I want to do:
( clickedObject === someDiv ) //returns true or false
What I tried
( $(e.target) === $('.selector') ); //returns a false negative.
My workaround
( $(e.target).attr('class') === $('.selector').attr('class') ); //works as intended, not so clean though.
What is the right way to compare the object I clicked to an object in the DOM?

To check if e.target has this class you can use the hasClass function.
if ($(e.target).hasClass("selector"))
Or, if you really want to compare objects, note that jQuery selectors return a collection of items, so I think you'll want
if (e.target === $('.selector')[0])

You're close. Use .is() instead:
if($(e.target).is('.selector')) {
// Your code
}
The trick here is that you wrap e.target in a jQuery object to allow it access to all the useful jQuery methods.
If you're just seeing whether e.target has a certain class, try using .hasClass() in place of .is():
if($(e.target).hasClass('selector')) {
// Your code
}
Either method works, although .hasClass() is a little clearer as to what the code does, and is faster than using .is()

If you want to match the element that the event is attached to you can use $(this), or if you want to find which element triggered the event use $(event.target).
Below is an example of both of these.
http://jsfiddle.net/Phunky/TbJef/
Unless you're using event delegation these will be the same though and if there the same element.

Obviously using .is() function is the best solution here.
If you find yourself doing such comparison, try to check if it is possible to use embedded jQuery mechanisms like this:
$(element).on("click", ".selector", function() {
alert("clicked");
});
Second argument in the .on() method is a target selector. When using this construction (read more: http://api.jquery.com/on/#direct-and-delegated-events) there will be no need to make any additional comparisons.
https://jsfiddle.net/m5zysufy/

$(document).click(function (e) {
e.stopPropagation();
var container = $('.dropdown-list').attr('class');
if ($(e.target).attr('class') == container) {
$('.dropdown-menu').slideToggle();
} else {
$('.header .header-elem .dropdown-nav .dropdown-menu').slideUp();
}
});

Related

Filter the $(this) element in loop jquery

I am trying to perform an action to other elements than the $(this) item
$('.items').click(function(){
var myitem = $(this);
$(".items").each(function() {
if (myitem == $(this)){
break;
} else {
//perform action
}
});
});
Where did I go wrong? Is there any better method?
Try to use the .not() function to filter out the current element,
$('.items').click(function(){
$('.items').not(this).each(function(){
//perform action here.
});
});
What went wrong?
When using the jQuery method (a.k.a. $) a new instance of the jQuery object is created, containing a list of elements matching your selector along side with a rich prototype of jQuery's methods.
Your mistake was to try and compare two different instances.
What you could have done was to compare the elements themselves by making the following changes:
// change this:
var myitem = $(this);
// to this:
var myitem = this;
// change this:
if (myitem == $(this)){
// to this:
if (myitem == this){
Unless you intend to use the jQuery object functionality there's no reason to initiate a new instance. Simply use the element itself when possible. It's a best practice to avoid such use cases. Performance wise.
Best solution
But the best solution in your case is what was mentioned in all other answers, using jQuery's not method to exclude the element from the newly created instance.
Using.not() to avoid
Try this
$(".items").not($(this)).each(function() {
});
OR
As per your code
$(".items").not(myitem).each(function() {
});
you can use not() to ignore the element which is clicked:
$(".items").not(this).each(function() {
});

jQuery compare two DOM object?

Clicking on an element:
$('.my_list').click(function(){
var selected_object = $(this);
$('.my_list').each(function(){
var current_object = $(this);
if( selected_object == current_object ) alert('FOUND IT !');
});
});
I don't know why, but I don't get the alert message "FOUND IT !".
You can use the jQuery.is function:
Check the current matched set of elements against a selector, element,
or jQuery object and return true if at least one of these elements
matches the given arguments.
if (selected_object.is(current_object)) {
...
}
An alternate solution is to use jQuery.get function to get the raw elements and compare them using == or === operator:
if (selected_object.get(0) == current_object.get(0)) {
...
}
jsFiddle demo
There's good answer provided... but it's important to understand, why you directly can't compare selectors in jQuery.
jQuery selectors return data structures which will never be equal in the sense of reference equality. So the only way to figure this out is to get DOM reference from the jQuery object and to compare DOM elements.
The simplest comparison of DOM reference for the above example would be:
selected_object.[0] == current_object.[0]

select html element id using jquery and .change()

I have several <select> boxes all using the same prefix and I would like to set up a recursive function to essentially do the work for me.
$('[id^="by_"]').change(function(e)
{
var elem = e;
console.log(e.value);
});
Based on this code is my intention pretty clear? Am I on the right track?
console prints out: undefined
I think you're on the right track - the selector you're using matches a prefix of "by_", and you're binding the change event to all of them. Make sure you put this in $(document).ready or similar. Are you having any problems with this code? Instead of using the e parameter, I would just use this inside of the function to refer to the element and $(this) to get the jQuery object of it. So to get the value, you'd use:
this.value
// or
$(this).val()
(ignore the e and elem stuff, although it wouldn't be a bad idea to store $(this) in something like elem so you can have a reference to it instead of re-creating the jQuery object every time you need it)
When using callbacks to events with jQuery, the (first) parameter of the callback is an event object that explains many things about the event that occurred ( http://api.jquery.com/category/events/event-object/ ) and does not hold the element - that's what this is for!
e in your code is the event object which has no value property, you should use this instead:
$('[id^="by_"]').change(function(e) {
var elem = this;
console.log(this.value);
});
Or if you want to use event object, you can use target property:
e.target.value
Since you're already using jQuery, why not something like this:
$('[id^="by_"]').change(function(e)
{
var $elem = $( this );
console.log( $elem.val() );
});
Isn't it more something like that:
$('[id^="by_"]').change(function()
{
console.log($('option:selected',this).val());
});
​
jsfiddle

How can I make it so that more than one ID will trigger using jQuery?

I have the following:
$('#editMenu', '#createContent', '#editContent')
.click(function () {
var $link = $(this);
if ($link.attr('data-disabled') === 'no') {
$link.attr('data-disabled', 'yes');
adminDialog($link);
}
return false;
});
However it seems like clicking on any of these does not work. Am I setting it up correctly?
What you are trying is multiple selector which should be written as a single string with comma separated selector. See below,
Change
$('#editMenu', '#createContent', '#editContent')
to
$('#editMenu, #createContent, #editContent')
jQuery allows for multiple selectors like so:
jQuery('selector1, selector2, selectorN')
so you would need:
$('#editMenu, #createContent, #editContent')
You can specify any number of selectors to combine into a single
result. This multiple expression combinator is an efficient way to
select disparate elements. The order of the DOM elements in the
returned jQuery object may not be identical, as they will be in
document order. An alternative to this combinator is the .add()
method.

Jquery Selector - Multiple Items

Say I have two jquery selections:
var txtA = $('#txtA');
var txtB = $('#txtB');
In order to attach the same event function, is this the neatest way, or am I missing an obvious piece of syntax or jquery wizardness?
$(jQuery.merge(txtA , txtB )).click(function () { alert('hello'); });
Thanks.
.add() should do (provided that you have already populated txtA and txtB and want the reuse those selections.):
txtA.add(txtB).click(function () {
alert('hello');
});
Given a jQuery object that represents a set of DOM elements, the .add() method constructs a new jQuery object from the union of those elements and the ones passed into the method. The argument to .add() can be pretty much anything that $() accepts, including a jQuery selector expression, references to DOM elements, or an HTML snippet.
$('#txtA, #txtB').click(function () { alert('hello'); });
may work for you
Here is what I have done:
$()
.add(elementOne)
.add(elementTwo)
.add(elementThree)
.click(function() {
alert('hello');
});
You can just do:
$("#txtA, #txtB").click(function () { alert('hello'); });
The same as a CSS selector, cool huh! :-)

Categories

Resources