javascript - Check if a HTML element exists before append -
i need way check if dynamically created hidden input element exists in document before appending it.
i know there similar questions, questions differs them because other questions seem basic appending of elements selectors e.g.
if ($('#button').length)
checks if element #button
id exists.
however in code, dynamically creating input
elements, name value attributes different. need if whole element exists 1 one in loop before append it. there way in jquery?
$('input[type=radio]:checked').each(function(){ //something if($('<input type="hidden" name="data[' + $(this).val() + ']" value="' + $(this).val() + '" />').length) { $('#addcharacters').append('<input type="hidden" name="data[' + $(this).val() + ']" value="' + $(this).val() + '" />'); } });
with jquery, can use .is()
function test whether element/sequence of elements match conditions specify. helpful don't have worry escaping strings. instance:
$('input:radio:checked').each(function(){ var cur = $(this).val(); if(!$('#addcharacters input:hidden') .is(function(i,e){ return e.value==cur && e.name=='data['+cur+']'; })) { // append new element } });
if have lot of radio elements check, you'll want move anonymous function somewhere else it's not created each radio element you're checking.
see expansive example in mini-guessing game here: https://jsfiddle.net/bv6abj7l/2/