将整个div括在<a>

时间:2019-01-29 11:36:58

标签: javascript jquery html

I have a div which I want to surround with an <a href>. I have the jQuery to add the <a href> after the div but I struggle to set it before and close it after the div.

This is the jQuery code I have:

$('.box_service').each(function() {
  var link = $(this).html();
  $(this).contents().wrap('<a href="example.com"></a>');
});

It results in this HTML:

<div class="row">
  <div class="box_service">
    <a href="example.com">
      <div class="inner-row"></div>
    </a>
  </div>
</div>

However my goal is this structure:

<div class="row">
  <a href="example.com">
    <div class="box_service">
      <div class="inner-row"></div>
    </div>
  </a>
</div>

I can't enter the div before because there are more boxes in this row so I would add the <a href> to everything in there

5 个答案:

答案 0 :(得分:2)

该问题是由于调用了contents()所致,这意味着您将元素包装在内部 .box_service中,而不是该元素本身。删除该方法调用。

还请注意,each()是多余的,您可以在一行中完成所需的操作:

$('.box_service').wrap('<a href="example.com"></a>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
  <div class="box_service">
    Box service #1
    <div class="inner-row">Inner row #1</div>
  </div>
</div>

<div class="row">
  <div class="box_service">
    Box service #2
    <div class="inner-row">Inner row #2</div>
  </div>
</div>

答案 1 :(得分:1)

.content将包裹您的div的内容,您想将div<a>包裹在一起,因此在wrap上调用div没有内容。

$('.box_service').each(function() {
  var link = $(this).html();
  $(this).wrap('<a href="example.com"></a>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
  <div class="box_service">
   
    <div class="inner-row"></div>

  </div>
</div>

答案 2 :(得分:1)

$('.box_service').each(function() {
  var link = $(this).html();
  $(this).wrap('<a href="example.com"></a>');
});

您只需要删除contents()之间的$(this).wrap(),因为contents()意味着您要包装$(this)的子级。

答案 3 :(得分:1)

删除.contents(),以便用类box-service包裹每个元素:

$('.box_service').each(function() {
  $(this).wrap('<a href="example.com"></a>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
  <div class="box_service">
    <a href="example.com">
      <div class="inner-row"></div>
    </a>
  </div>
</div>

答案 4 :(得分:0)

$('.box_service').wrap('<a href="example.com"></a>');