Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if element exists within DIV

Tags:

jquery

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(); 
like image 801
Dan Avatar asked Nov 25 '11 17:11

Dan


People also ask

How do I check if an element is present in a Web page?

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.

How do you check if an element is present in HTML?

var element = document. getElementById('elementId'); if (typeof(element) != 'undefined' && element != null) { // Exists. }

How do I check if an element exists in Dom?

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.

How do you check the element is present or not in jQuery?

Syntax: $(element).is(":visible"); Example 1: This example uses :visible selector to check an element is visible or not using jQuery.


2 Answers

This should do it..

$('.tag').on('click', function(event) {

    var self = $(this);
    if (self.closest('#crate').length) {
        // do nothing
    }
    else {
        self.appendTo('#crate');
    }

});
like image 99
Gabriele Petrioli Avatar answered Nov 27 '22 06:11

Gabriele Petrioli


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');
    }
});
like image 37
jfriend00 Avatar answered Nov 27 '22 06:11

jfriend00