Reputation: 38842
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
Reputation:
check if element is already appended:
alert($(this).parent().length?'appended':'not appended');
Upvotes: 2
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
Reputation: 79032
You are using mootools and not jQuery.
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
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
Reputation: 13134
$("#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
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