jQuery - find and manipulate matched attribute values

<div id="veg">
<a title="Tree" href="x.html"><a>
<a title="Leaf" href="y.html"><a>
</div>

<div id="pic">
<img title="Tree" src="tree_1.jpg" />
<img title="Leaf" src="leaf_1.jpg" />
<img title="Leaf" src="leaf_2.jpg" /> 
</div>

The above is a primitive and unlikely example, but lets say I want to achieve the following outcome for the two anchors:

<a title="Tree" href="x.html">Tree<a>
<a title="Leaf" href="y.html">Leaf<a> 

Each anchor is unique, but the title attribute may match the exact title of one or more images. Where a match is found, either once or more, the title text is copied - once - into the anchor element.

How to do with jQuery?

Key here is that both anchors are in the div with id “veg”, so you could just do :


$('#veg a').each( function() {
  $(this).text( $(this).attr('title') );
});

:slight_smile:

Thanks for your lightning response. That’s certainly a suitable solution for the inadequate example I provided. :slight_smile:

Let’s say I want to be difficult, and insist that the process requires the match between title attributes. How would this be achieved?

Like this?


$('a').each(function() {
  if ($('[title="' + $(this).attr('title') + '"]').size() > 1) {
    $(this).text( $(this).attr('title') );
  }
});

Yep, that works mighty fine (especially with correctly closed anchors :blush:).

Thanks again.