Search code examples
jqueryhtmltooltip

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.


Solution

  • Try like this

    $( ".list li" ).each(function() {
        var thisAltText = $(this).children().attr('alt');
        $(this).children().attr('title', thisAltText);
    });
    

    Or

    $( ".list li a" ).each(function( index ) {
        var thisAltText = $(this).attr('alt');
        $(this).attr('title', thisAltText);
    });
    

    Or

    $( ".list li" ).each(function( index ) {
        var thisAltText = $(this).find('img').attr('alt');
        $(this).find('img').attr('title', thisAltText);
    });
    

    Or

    $( ".list" ).children().each(function( index ) {
        var thisAltText = $(this).find('img').attr('alt');
        $(this).find('img').attr('title', thisAltText);
    });
    

    Play here https://jsfiddle.net/47jgmzju/