Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 733
Mellon Avatar asked Oct 31 '11 08:10

Mellon


People also ask

How do I know if my element has been clicked?

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.

What does the append function do in jQuery?

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.

Does jQuery append return the element?

Element. append() has no return value, whereas Node. appendChild() returns the appended Node object.

What is the difference between append and after in jQuery?

. 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.


1 Answers

  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>");
});
like image 57
Samuel Liew Avatar answered Oct 07 '22 07:10

Samuel Liew