简体   繁体   中英

Add <i> tag inside of an anchor tag just before the <span> tag using jQuery

I have this html code:

<div id="outerDiv" class="cls">
  <ul id="ul">
    <li id="li">
      <a id="link1" href="#">
        <span>Click me</span>
      </a>
    </li>
  </ul>
</div>

How do I in jQuery add an <i> tag just before the <span> element so the HTML is rendered as:

<div id="outerDiv" class="cls">
  <ul id="ul">
    <li id="li">
      <a id="link1" href="#">
        <i class="zmdi zmdi-check"></i>
        <span>Click me</span>
      </a>
    </li>
  </ul>
</div>

You can use jQuery's .before() :

Insert content, specified by the parameter, before each element in the set of matched elements.

Demo:

 $(document).ready(function(){ $('#link1 span').before('<i class="zmdi zmdi-check">Some Text</i>'); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="outerDiv" class="cls"> <ul id="ul"> <li id="li"> <a id="link1" href="#"> <span>Click me</span> </a> </li> </ul> </div>

.before script code add bottom of your code like below code. it will work

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="outerDiv" class="cls">
  <ul id="ul">
      <li id="li">
          <a id="link1" href="#">
              <span>Click me</span>
          </a>
      </li>
  </ul>
</div>
<script type="text/javascript">
  $('#link1 span').before('<i class="zmdi zmdi-check">Some Text</i>');  
</script>

Please add jquery-

<script type="text/javascript">
  $( "<i></i>" ).insertBefore( "#link1 span" );
  $('#link1 i').addClass('zmdi zmdi-check');
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM