Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
40
rated 0 times [  43] [ 3]  / answers: 1 / hits: 28765  / 7 Years ago, sun, march 19, 2017, 12:00:00

I would like to append a div only if it's not already there. I am trying with this but it doesn't work:



$('#method_id').on('change', function (e) {

if ($(this).find(option:selected).data('method-column-id') != 1) {
if ($('#column_message').next('div').length)
$('#column_message')
.append('<div id=warning_message class=alert alert-danger><strong>Warning!</strong> Installed column and method do not match</div>');
} else {
$('.form-group').find('#column_message>.alert').remove();
}
});


And if I remove the second if-clause, it gets appended every time I select an option which passes first if-clause



Here is the HTML



<!-- Warning message -->
<div class=form-group>
<label for=group class=col-md-2 control-label></label>
<div id=column_message class=col-md-6>
</div>
</div>

More From » jquery

 Answers
8

In order to check if an element exists, you need to find a selector that matches only that element and check if the length of the jQuery object is equal to 0 or not, like so:



if ($('#unique-selector').length === 0) {
// code to run if it isn't there
}
else {
// code to run if it is there
}

[#58484] Thursday, March 16, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
taylert

Total Points: 627
Total Questions: 91
Total Answers: 108

Location: Mayotte
Member since Mon, Sep 12, 2022
2 Years ago
taylert questions
;