I want to, on click, move an element inside a div unless it's already inside it. I was thinking something like...
Click tag > If element is in div do nothing > Else move element into div
http://jsfiddle.net/establish/Xhhe8/
HTML
<ul>
<li><a href="#" class="tag">Art</a></li>
<li><a href="#" class="tag">Computing</a></li>
<li><a href="#" class="tag">Design</a></li>
</ul>
<div id="crate">
</div>
jQuery
$('.tag').on('click', function(event) {
if ($('#crate').has(this)) {
// do nothing
}
else {
$(this).appendTo('#crate');
}
});
It doesn't work. Also not sure how to represent 'do nothing', usually I just use a singular IF statement so no need to represent it. Can I do this to 'do nothing' and disable the click?
$(this).off();
Using driver. In order to check if an element is present on a webpage, we make use of driver. findElements() method. As we know that driver. findElements() method returns a list of webElements located by the “By Locator” passed as parameter.
var element = document. getElementById('elementId'); if (typeof(element) != 'undefined' && element != null) { // Exists. }
To check if an element does not exist in the DOM: Use the getElementById or querySelector methods to select the element. Check if the stored value is equal to null . If the value is equal to null , the element does not exist in the DOM.
Syntax: $(element).is(":visible"); Example 1: This example uses :visible selector to check an element is visible or not using jQuery.
This should do it..
$('.tag').on('click', function(event) {
var self = $(this);
if (self.closest('#crate').length) {
// do nothing
}
else {
self.appendTo('#crate');
}
});
Gaby's answer will work, but I'd prefer structuring it without the empty if
block like this:
$('.tag').on('click', function(event) {
var self = $(this);
if (self.closest('#crate').length == 0) {
self.appendTo('#crate');
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With