smurtagh smurtagh - 1 month ago 6
jQuery Question

How do I use JQuery to change one html attribute's value to equal a different attribute's value?

With JQuery on document load, I am trying to select each

<img>
and give it a new attribute
title
and set it to equal the value of the attribute
alt
. The
title
is what is supposed to appear in the tooltip when the user hovers over the element. Using the console, I seem to be able to select each element effectively, but something seems to go wrong when I put it all together.

The HTML:

<ul class="list">

<li><img href="#" src="url" data-toggle="tooltip" data-placement="right" alt="first-tooltip"></li>

<li><img href="#" src="url" data-toggle="tooltip" data-placement="right" alt="second-tooltip"></li>

<li><img href="#" src="url" data-toggle="tooltip" data-placement="right" alt="third-tooltip"></li>

</ul>


The JS:

$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip(); //enable tooltips

$('.list li').children().each( function(){ //perform function on each <a>
var thisAltText = $(this).attr('alt'); //select the alt value
$(this).attr('title', thisAltText); //set title value to equal alt value
});
});


As you can see, this is not working: http://codepen.io/shawnmurtagh/pen/ZpVgkz

FYI - I am using
.children()
because I need to select different list items in my actual project.

Answer

Do it like this:

$(document).ready(function(){

        $('.list li').children().each( function(){  //perform function on each <a>
          var thisAltText = $(this).attr('alt');  //select the alt value
          $(this).attr('title', thisAltText);  //set title value to equal alt value
        });
       $('[data-toggle="tooltip"]').tooltip();   //enable tooltips

    });