Chain Trap Chain Trap - 3 months ago 8
jQuery Question

JavaScript - Append to an element that cannot contain children using jQuery

I have several

<div>
elements for example, each one has the same class and contains 2 sibling. I want to append an element to the last sibling but that element cannot contain a children...

E.g

<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox"/> Checkbox 1
</label>
</div>
<div class="checkbox ">
<label>
<input type="checkbox "/> Checkbox 2
</label>
</div>
<div class="checkbox ">
<label>
<input type="checkbox "/> Checkbox 3
</label>
</div>
</div><!-- form-group -->


So my jQuery code is the following but it didn't work...

$(function() {
var div = $("div"),
$element = '<span></span>';
div.each(function(i, el) {
if (el.hasClass("class-name")) {
$(el).nextAll().eq(1).append($element);
}
});
});



I've included an
IF
statement for veryfication and only append the
element to the target (here I'm pointing to the
<input>
element as
the target) within the
<div>
only so the other elements will not be
included.


Any idea how to achieve that in this case?

Thanks.

Answer

Not knowing your exact intent regarding the "children" comment I present three

This appends TO the last element:

$(function() {
  var div = $("div.class-name"),
    $element = '<span></span>';
  div.last().append($element);
});

This appends a new span AFTER the last one:

$(function() {
  var div = $("div.class-name"),
    $element = '<span></span>';
  div.last().after($element);
});

This replaces the last elements content with the span:

$(function() {
  var div = $("div.class-name"),
    $element = '<span></span>';
  div.last().html($element);
});

NOTE After your edit, I made the assumption you want to append a span after the last checkbox elements label so this does that:

$(function() {
  var div = $("div.checkbox");
  var lastelementwithnochildren = div.find('*:not(:has("*"))').last();
  $element = '<span>howdy</span>';
  lastelementwithnochildren.parent().append($element);
});

IF you want the span before the label text just after the input, change the last line to:

lastelementwithnochildren.after($element);