× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

How to use jQuery to dynamically change the link of an anchor tag based on the attribute of its child

Rowland Ekemezie
Oct 25, 2016
<p>Using jQuery to manipulate the content of a web page can be a bit tricky if you don't get the flow.</p> <p><strong>Context: </strong></p> <p>1) You have a page of over 500 images and wants to find an <strong>img</strong> tag with alt attribute <strong>'You are good'.</strong></p> <p>2) You want to change the <strong>href</strong> of the anchor tag whose child is an <strong>img</strong> tag.</p> <p><strong>Action:</strong></p> <p><strong>1) </strong>Iterate through all the anchor tag on the page.</p> <p>2) Add a conditional to check the attribute of each child image</p> <p>3) Replace the <strong>href</strong> of the anchor tag.</p> <p><em><strong>$('a').each(function() {</strong></em></p> <p><em><strong>  if($(this).children('img').attr('alt', 'You are good')){</strong></em></p> <p><em><strong>     $(this).attr('href', '&lt;The new href you want to substitute&gt;)<br>   }</strong></em></p> <p><em><strong>});</strong></em><br>  </p> <p>P.S: There are other ways to achieve this but I prefer an explicit approach.</p> <p> </p> <p> </p>
comments powered by Disqus