Add something after the “n” element using jQuery

后端 未结 6 1665
忘了有多久
忘了有多久 2020-12-13 08:49

For a markup like

div 1
div 2
div 3
相关标签:
6条回答
  • 2020-12-13 09:29

    Try it like this:

    $("#holder > div:nth-child(2n)").after("<div>insert here</div>");
    

    It will insert the <div>insert here</div> after every 2nd row:

    $("#holder > div:nth-child(2)").after("<div>insert here</div>");
    
    0 讨论(0)
  • 2020-12-13 09:30

    Try the CSS selector :nth-child():

    $("#holder > div:nth-child(2)").after("<div>foobar</div>");
    

    See also the example on the jQuery page of the :nth-child() selector.

    0 讨论(0)
  • 2020-12-13 09:30

    $("#holder div:eq(1)") will select the second child div of the #holder div. (:eq() selector info). Then use the .after() function to append content.

    0 讨论(0)
  • 2020-12-13 09:34

    use the :eq(index) or :nth-child(index/even/odd/equation) selector in combination with the append(content) or after(content) function.

    for example, assuming this code:

    <div id="holder">
        <div>div 1</div>
        <div>div 2</div>
        <div>div 3</div>
        <div>div 4</div>
    </div>
    using append like this
    $("#holder>div:eq(1)").append("<div>inserted div</div>");
    or this
    $("#holder>div:nth-child(2)").append("<div>inserted div</div>");
    will give you
    
    <div id="holder">
        <div>div 1</div>
        <div>div 2<div>inserted div</div></div>
        <div>div 3</div>
        <div>div 4</div>
    </div>
    while using after like this
    $("#holder>div:eq(1)").after("<div>inserted div</div>");
    or this
    $("#holder>div:nth-child(2)").after("<div>inserted div</div>");
    will give you
    
    <div id="holder">
        <div>div 1</div>
        <div>div 2</div>
        <div>inserted div</div>
        <div>div 3</div>
        <div>div 4</div>
    </div>

    using :nth-child can be useful as it enables you to set content every n amount of elements. also, the index of :nth-child starts at 1 while the index of :eq starts at 0

    for example, using

    $("#holder>div:nth-child(2n)").after("<div>inserted div</div>");
    will give you
    
    <div id="holder">
        <div>div 1</div>
        <div>div 2</div>
        <div>inserted div</div>
        <div>div 3</div>
        <div>div 4</div>
        <div>inserted div</div>
    </div>

    0 讨论(0)
  • 2020-12-13 09:41

    Use insertAfter(selector)

    .insertAfter()

    0 讨论(0)
  • 2020-12-13 09:50

    use this

     $("ul li:nth-child(4n)").add('ul li:last').after("<div style='clear:both;'>&nbsp;</div>");
    
    0 讨论(0)
提交回复
热议问题