如何找到DIVS的ID,并将这些名称作为类分配给其他DIVS?

时间:2014-10-30 18:33:08

标签: javascript jquery addclass

我对jquery相当新鲜,无法解决这个问题。我有3个不同id的div,但都以“sharedform”开头。我想循环遍历这些div,获取每个id并将其作为标识类分配给每个前面的'slideHead'div。任何帮助将不胜感激!

HMTL:

<div class="slideHead">
</div>
<div class="drawer">
  <div id="sharedform.upload_image">
          <p></p>
  </div>
</div>
<div class="slideHead">
</div>
<div class="drawer">
   <div id="sharedform.Event">
       <p></p>
   </div>
</div>
<div class="slideHead">
</div>
<div class="drawer">
    <div id="sharedform.BackGround_All">
        <p></p>
    </div>
 </div>

jquery的:

var $getclass = $(".drawer");
    addclass = $getclass.find('[id^="sharedform"]').attr('id');
$(".slideHead").addClass(addclass);

2 个答案:

答案 0 :(得分:3)

我建议:

// get all elements whose id starts with 'sharedform', iterate over that collection:
$('div[id^=sharedform]').each(function (){
    // find the parent of the 'this' element:
    $(this).parent()
    // find the previous element, if it matches the passed-in selector:
    .prev('.slideHead')
    // add the id of the element we initially selected as a class:
    .addClass(this.id);
});

$('div[id^=sharedform]').each(function() {
  $(this).parent().prev('.slideHead').addClass(this.id);
});
div {
  width: 80%;
  margin: 0 auto;
  min-height: 2em;
  padding: 0.5em;
  border: 1px solid #000;
}
.slideHead {
  background-color: #f00;
}
.slideHead.sharedform\.something {
  background-color: #0f0;
}
<div class="slideHead"></div>
<div>
  <div id="sharedform.something">some text in the div</div>
</div>

但请注意,考虑到.中包含句点(id),这些类名称存在问题。

答案 1 :(得分:0)

这应该这样做:

$('[id^=sharedform]').each(function() {
    $(this).closest('.drawer').prev().addClass( this.id );
});

$('[id^=sharedform]').each(function() {
        $(this).closest('.drawer').prev().addClass( this.id );
    });

var newHTML = $('body').html(),
    out = $('<pre/>', {class:'out'}).appendTo( 'body' );

out.text( 'NEW HTML\n' + newHTML );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slideHead">
</div>
<div class="drawer">
  <div id="sharedform.upload_image">
          <p></p>
  </div>
</div>
<div class="slideHead">
</div>
<div class="drawer">
   <div id="sharedform.Event">
       <p></p>
   </div>
</div>
<div class="slideHead">
</div>
<div class="drawer">
    <div id="sharedform.BackGround_All">
        <p></p>
    </div>
 </div>