Skip to content Skip to sidebar Skip to footer

About Jquery Append() And How To Check If An Element Has Been Appended

I made a very simple button click event handler, I would like to have

element be appended when button clicked, you can check my code here:

&l

Solution 1:

  1. You are using mootools and not jQuery.

  2. To check if your element exists

if($('#other').length > 0)

So if you do not want to append the element twice:

$("#search_btn").click(function() {
    if($('#other').length == 0) {
        $("#wrapper").append("<p id='other'>I am here</p>");
    }
});

Or, you can use the .one(function)[doc]:

$("#search_btn").one('click', function() {
    $("#wrapper").append("<p id='other'>I am here</p>");
});

Solution 2:

1) jsFiddle loads in MooTools by default, you need to include jQuery for this to work. There is not a reason in the world why that example wouldn't work. (Assuming that the $ is actually mapped to the jQuery object, that is.)

2) You can check the nextSibling of a DOMElement, or use the next() jQuery method, like so:

if(!$('#something').next().length) {
   //nonext sibling.
}

Solution 3:

http://jsfiddle.net/j36ye/17/

$("#search_btn").click(function(){
    if(($('#other').length) == 0) {
        $("#wrapper").append("<p id='other'>I am here</p>");
    }
    returnfalse
});

Or

var other_appended = false;

$("#search_btn").click(function(){
    if(other_appended == false) {
         $("#wrapper").append("<p id='other'>I am here</p>");
          other_appended = true;
    }
    returnfalse;
});

Solution 4:

How to check if an element exists:

if($("p#other").length > 0) {
    // a p element withid"other" exists
}
else {
    // a p element withid"other" does not exist
}

Solution 5:

Your fiddle is using the moo tools framework. Change it to use the jquery framework on the left and it works. See http://jsfiddle.net/KxGsj/

Post a Comment for "About Jquery Append() And How To Check If An Element Has Been Appended"