Dark Mark Dark Mark - 1 year ago 60
HTML Question

Adding an element after another element that has no parent

I want to implement a reusable UI element in jQuery where I add a button after an HTML element.

There are two scenarios how the element will be used: statically declared in the HTML and dynamically created in JS. I have problems implementing the second use case.

The static use case:

<span class=".ui-element'>Content</span>

I pick up the element in jQuery and put my button after the span:


This works fine so far.

A problem occurs when using the same technique on a dynamically created span:

var the_span = $("<span>").text("Content").after(the_button);
return the_span; // caller is responsible for adding it the DOM

This does not work: there is no button in the DOM after this. I guess it's because the span has no parent yet, while the statically declared span has a parent?

This can be solved by

  1. introducing a wrapper element around the dynamically created span:

    var wrapper = element.wrap($('span')).parent();
    wrapper.append(the_span, the_button);

    Now my function has to return the wrapper instead of the span, so the caller can add it to the DOM. This is unexpected behavior and breaks chaining. I also don't want to require a wrapper in the static use case, because it's not needed there.

  2. the_span.append(the_button);

    I can't use this solution, because I want to be able to use .text() and .html() on the original span afterwards, which would remove the button.

  3. require that the span has been added to the DOM before adding my button. This works, but I'd prefer a solution that works without requiring this.

How can I solve this?

Answer Source

You should use .add instead of .after, as following:

var the_span = $("<span>").text("Content").add(the_button);
return the_span; // caller is responsible for adding it the DOM

Using an .add will add the element to the jQuery selection.

See it in work: https://jsfiddle.net/nbm83e85/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download