grimblefritz grimblefritz - 4 months ago 25
jQuery Question

insert an anchor tag using jquery

I have an app (that I didn't write) that generates the following:

<div class="page-header"><h1>
<div class="row">
<div class="col-sm-8">
<a href="item_view.php">
<img src="icons/item.png"> Purchased Items</a>
</div>
<!-- other tags &c. -->
</div></h1>
</div>


I have access to a javascript hook, and jquery is available, that I can make customizations in. The end result I want is:

<div class="page-header"><h1>
<div class="row">
<div class="col-sm-8">
<a href="order_view.php">
<img src="icons/order.png"> Order Info</a>
<a href="item_view.php">
<img src="icons/item.png"> Purchased Items</a>
</div>
<!-- other tags &c. -->
</div></h1>
</div>


I've tried everything I can think of, with no success.

HOW DO I:

Using jQuery, select the "Purchased Items" anchor, and insert the "Order Info" anchor+image before it?

Thanks!

Answer

What you want is basically selecting the anchor and prepending it with two new elements:

$(document).ready(function() {
  var template = "<a href='order_view.php'><img src='icons/order.png'> Order Info</a>";
  $("a[href='item_view.php']").prepend(template);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="page-header">
  <h1>
      <div class="row">
        <div class="col-sm-8">
          <a href="item_view.php">
            <img src="icons/item.png"> Purchased Items</a>
        </div>
        <!-- other tags &c. -->
      </div>
  </h1>
</div>

Comments