使用JQuery向嵌套元素添加元素

时间:2014-01-23 23:51:50

标签: jquery dom

I have a document structure that looks similar to this:

<article id="post1" class="post-5 page type-page" > 
   <section class = "holder clearfix">

     <div class = "four columns">
      <a title class = "single-image short-link" href "http://whatever.com" target = "self">
        </a>
     </div>

     <div class = "four columns">
      <a title class = "single-image short-link" href "http://whatever.com" target = "self">
        </a>
     </div>

     <div class = "four columns">
      <a title class = "single-image short-link" href "http://whatever.com" target = "self">
        </a>
     </div>

     <div class = "four columns">
      <a title class = "single-image short-link" href "http://whatever.com" target = "self">
        </a>
     </div>


 </section>
</article>

我想要做的是使用JQuery为每个 a 元素添加一个带有类和唯一ID的div。

最终结果看起来像这样

<article id="post1" class="post-5 page type-page" > 
   <section class = "holder clearfix">

     <div class = "four columns">
      <a title class = "single-image short-link" href "http://whatever.com" target = "self">

           <div id="button1" class = "shiny-button"> </div>     // unique ID
        </a>
     </div>

     <div class = "four columns">
      <a title class = "single-image short-link" href "http://whatever.com" target = "self">

            <div id="button2" class = "shiny-button"> </div>     // unique ID
        </a>
     </div>

     <div class = "four columns">
      <a title class = "single-image short-link" href "http://whatever.com" target = "self">
            <div id="button3" class = "shiny-button"> </div>     // unique ID
        </a>
     </div>

     <div class = "four columns">
      <a title class = "single-image short-link" href "http://whatever.com" target = "self">     
          <div id="button4" class = "shiny-button"> </div>     // unique ID
        </a>
     </div>


 </section>
</article>

到目前为止,以下JQuery代码让我大约一半:

$('<div/>', {
    class:'shiny-button',
}).appendTo('.single-image');

我尝试使用类似于以下内容的代码,但我似乎无法正确使用

$('<div/>', {
    class:'shiny-button',
    id: 'button1',
}).appendTo('.holder .four:nth-child(1)');

谢谢。

2 个答案:

答案 0 :(得分:0)

尝试使用每个。所以

$('.single-image').each(function(index){
    //Append new element to $(this)
    //index will be a counter
    //$(this) = the current $('.single-image') element
});

我相信你可以使用索引是唯一的。我记不住了,但jQuery中记录了.each()函数。

答案 1 :(得分:0)

尝试

$('#post1 .single-image').append(function(i){
    return '<div id="button'+(i+1)+'" class = "shiny-button"> dd</div>'
})

演示:Fiddle