skip to Main Content

I have an element created that I append various children to. They are not all similar in any selector necessarily, but they are all direct children.

I’d like to insert an element between them to unify them with "and", but I’m spacing on how I could do that.

For instance;

<div id="parent">
   <span>This sentence is one</span>
   <span>this sentence is another</span>
</div>

should more resemble

<div id="parent">
  <span>This sentence is one</span>
  <span>&nbsp;and&nbsp;</span>
  <span>this sentence is another</span>
</div>

All are children of the top level div but some may be a span while others an a. I cannot add a class nor ID to them. There is also an unknown amount of children, only certain there are more than 2.

My idea was to get the children of the parent div & then use .join("&nbsp;and&nbsp;") but I can’t seem to find a cohesive way to do so. Does similar logic exist? I’d have scrubbed docs a bit more, but they seem to be having some slowness issues today.

2

Answers


  1. Use .after():

    $('#parent *:not(:last)').after('<span>&nbsp;and&nbsp;</span>');
    
    Login or Signup to reply.
  2. Use .after() to add the span after each child except the last one. Use .slice() to select that range of children.

    let children = $("#parent").children();
    children.slice(0, -1).after('<span>&nbsp;and&nbsp;</span>`enter code here`');
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="parent">
       <span>This sentence is one</span>
       <span>this sentence is another</span>
       <span>this sentence is third</span>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search