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...
To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked.
append( function ) A function that returns an HTML string, DOM element(s), text node(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments.
Element. append() has no return value, whereas Node. appendChild() returns the appended Node object.
. append() adds the parameter element inside the selector element's tag at the very end whereas the . after() adds the parameter element after the element's tag.
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>");
});
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