Add something after the “n” element using jQuery

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

For a markup like

div 1
div 2
div 3
6条回答
  •  我在风中等你
    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 1
    div 2
    div 3
    div 4
    using append like this
    $("#holder>div:eq(1)").append("
    inserted div
    ");
    or this
    $("#holder>div:nth-child(2)").append("
    inserted div
    ");
    will give you
    
    
    div 1
    div 2
    inserted div
    div 3
    div 4
    while using after like this
    $("#holder>div:eq(1)").after("
    inserted div
    ");
    or this
    $("#holder>div:nth-child(2)").after("
    inserted div
    ");
    will give you
    
    
    div 1
    div 2
    inserted div
    div 3
    div 4

    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("
    inserted div
    ");
    will give you
    
    
    div 1
    div 2
    inserted div
    div 3
    div 4
    inserted div

提交回复
热议问题