Checking for the presence of an element on the page, jQuery

In the process of executing the function, a button is created as follows:

$('#score').append('<input id="newTry" type="button" value="Try again?"/>');

It is necessary that when the function is executed again, initiated by pressing the button, it is not created again at this point of execution. How can I check for the presence of such an element on the page?

Author: edithpifpaf, 2017-08-12

1 answers

The check can be done by. length - the number of elements found. If 0 (false) then create:

function createButton(){
  console.log($('#newTry').length);
  if(!$('#newTry').length) $('#score').append('<input id="newTry" type="button" value="Try again?"/>');
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="score"></div>
<button onclick="createButton()">Create Button</button>
 4
Author: Horchynskyi, 2017-08-12 10:16:20