Collins
Collins

Reputation: 1159

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?

Upvotes: 2

Views: 2775

Answers (3)

gschambial
gschambial

Reputation: 1391

Here is a WORKING FIDDLE for you.

$(function(){

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

});

Upvotes: 0

andre mcgruder
andre mcgruder

Reputation: 1520

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>');

Upvotes: 2

Mohammad
Mohammad

Reputation: 21499

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>

Upvotes: 2

Related Questions