javascriptjqueryhtmlattributesjquery-append

How to get title attribute of element and insert it after element using jquery?


I have a list with list elements like this...

<li class="first leaf">
  <a href="/admin/store/orders/view" title="View and process the orders.">View orders</a>
</li>

And I want to take the title attribute and append it as a div after the <a> like this...

<li class="first leaf">
  <a href="/admin/store/orders/view" title="View and process the orders.">View orders</a>
  <div>View and process the orders.</div>
</li>

So far, I am here...

(function ($) {    
  $('#block-menu-menu-admin-welcome li a').each(function () {
    $(this).append('<div>' + $(this).attr('title') + '</div>');
  });
})(jQuery);

But it isn't working. Can anyone help?


Solution

  • JQuery .append() insert html to selected element but you need to insert html after selected element. Use .after() instead.

    $('#block-menu-menu-admin-welcome li a').each(function () {
        $(this).after('<div>' + $(this).attr('title') + '</div>');
    });
    

    $('a').each(function(){
        $(this).after('<div>' + this.title + '</div>');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <ul>
      <li class="first leaf">
        <a href="/admin/store/orders/view" title="View and process the orders.">View orders</a>
      </li>
    </ul>