Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append an element with jQuery unless it exists already?

Tags:

jquery

I have this jQuery function that appends a span labelled "optional" to a label if no option is set in the select box.

function setLabel() {
    var label=$('label[for=person_address]');
    if ($('select#person_organisation_id').val().length != 0) {
      label.append(' <span>— optional</span>');     
    } else {
  label.children().remove();            
  } 
}

Right now this adds a new span to the label every time I select a new option. How can I check if a span already exists and only add a span if there is none already?

Thanks for any help...

like image 549
Tintin81 Avatar asked Dec 06 '25 20:12

Tintin81


1 Answers

Try the following:

label.not(":has(span)").append(" <span>— optional</span>");
like image 186
VisioN Avatar answered Dec 08 '25 10:12

VisioN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!