Mellon
Mellon

Reputation: 38842

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 <p> element be appended when button clicked, you can check my code here:

<div id="wrapper">
    <input id="search_btn" value="Search" type="button">
</div>
$("#search_btn").click(function(){
    $("#wrapper").append("<p id='other'>I am here</p>");
});

I have two questions to ask:

1, why my .append() does not work as I expected (that's append the <p> element)

2. in jQuery, how to check if some element is already appended? For example how to check if <p id="other"> has already appended in my case?

-------------------- update -------------------------------------------

Please check my updated code here.

So, only the 2nd question remains...

Upvotes: 14

Views: 41652

Answers (6)

user669677
user669677

Reputation:

check if element is already appended:

alert($(this).parent().length?'appended':'not appended');

Upvotes: 2

Tom
Tom

Reputation: 5201

How to check if an element exists:

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

Upvotes: 2

Samuel Liew
Samuel Liew

Reputation: 79032

  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>");
});

Upvotes: 30

Jacob Relkin
Jacob Relkin

Reputation: 163238

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) {
   //no next sibling.
}

Upvotes: 4

Marco Johannesen
Marco Johannesen

Reputation: 13134

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

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

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;
    }
    return false;
});

Upvotes: 2

Moin Zaman
Moin Zaman

Reputation: 25445

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/

Upvotes: 1

Related Questions