简体   繁体   中英

Check if a HTML element exists before append

I need a way to check if a dynamically created hidden input element exists in the document before appending it.

I know there are similar questions, but my questions differs from them because the other questions seem to be for basic appending of elements with selectors eg

if ($('#button').length)

checks if an element with a #button id already exists.

However in my code, as I am dynamically creating input elements, their name value attributes will be different. So I need to if the whole element exists one by one in the loop before I append it. Is there a way to do this in jQuery?

$('input[type=radio]:checked').each(function(){

//Something like this
if($('<input type="hidden" name="data[' + $(this).val() + ']" value="' + $(this).val() + '" />').length)
 {
 $('#addCharacters').append('<input type="hidden" name="data[' + $(this).val() + ']" value="' + $(this).val() + '" />');
 }
});

您需要使用倍数属性等于选择器:

if($('input[type="hidden"][name="data[' + $(this).val() + '"][value="' + $(this).val() + '"]').length)

With jQuery, you can use the .is() function to test whether an element/sequence of elements match conditions you specify. This is especially helpful so you don't have to worry about escaping strings. For 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 you have a lot of radio elements to check, you'll probably want to move the anonymous function somewhere else so it's not created for each radio element that you're checking.

See an expansive example in a mini-guessing game here: https://jsfiddle.net/bv6abj7L/2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM