2

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?

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Collins
  • 1,069
  • 14
  • 35
  • 2
    Did you want `.after()` instead of `.append()`? `.after()` [works fine for me](https://jsfiddle.net/j08691/o3qohz4n/) – j08691 Oct 19 '16 at 14:09

3 Answers3

2

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>
Mohammad
  • 21,175
  • 15
  • 55
  • 84
  • Thanks, but cant get this to work still. I printed a message with console.log ( 'test' ); and it showed in console, so i know jquery and the js file are being noticed. – Collins Oct 19 '16 at 14:51
  • @Collins The code work in snippet. So your code has problem. Check console for error. – Mohammad Oct 19 '16 at 14:57
  • No errors in console. Thank you for your help, I can see it works, I'll have to debug on my end – Collins Oct 19 '16 at 14:58
2

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>');
andre mcgruder
  • 1,120
  • 1
  • 9
  • 12
0

Here is a WORKING FIDDLE for you.

$(function(){

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

});
gschambial
  • 1,383
  • 2
  • 11
  • 22