添加<a> tag into a class with javascript

时间:2017-08-18 00:17:25

标签: javascript jquery html

i want to add link to label tag the code is this:

    <div class="swatchinput">
       <label selectid="pa_color" class="attribute_pa_color_black wcvaswatchlabel wcvasquare"</label>
     <div>

how i can add <a href="test.com"> then close that with after </label> to make link. i use this code with jquery but dosnt work fine

 $(".swatchinput").before( "<a href='https://yenial.ir'>" );
      $( "</a>" ).appendTo( ".attribute_pa_color_black" ); 

1 个答案:

答案 0 :(得分:1)

看起来你不明白HTML,DOM,jQuery是如何工作的。你需要知道的是:

  1. 你不能有不正确的嵌套(如<a></label></a>,这就是你所要求的我相信的。)
  2. 没有像$("</a>")这样的选择器。任何以/开头的标记都是结尾标记。
  3. 您无法使用<label>
  4. 包裹<a>
  5. 您尚未正确关闭<label>的起始标记。
  6. 您尚未正确关闭href属性。
  7. 您不能在<a><label>或反之亦然。
  8. 你仍然可以继续做你想做的事,但浏览器会推出它。因此,考虑到以上几点,您需要的是:

    $(".swatchinput").wrapInner( "<a href='https://yenial.ir'>" ); // Or
    $(".swatchinput").append( "<a href='https://yenial.ir'>" );
    

    工作代码段

    $(function () {
      $(".swatchinput").append( "<a href='https://yenial.ir'>" );
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="swatchinput">
      <label selectid="pa_color" class="attribute_pa_color_black wcvaswatchlabel wcvasquare"></label>
    </div>

    但是当上面的代码运行时(将<a>附加到<label>),浏览器会这样做:

    preview