View ord" /> View ord" /> View ord"/>

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

2.7k views Asked by At

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?

3

There are 3 answers

3
Mohammad On BEST ANSWER

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>

0
andre mcgruder On

Your first this in your loop is a reference to the anchor. You have to comb out of that to its parent element and append to that.

$(this).parent().append('<div>' + $(this).attr('title') + '</div>');
0
gschambial On

Here is a WORKING FIDDLE for you.

$(function(){

     $('.first').append($('.first a').attr('title'));

});