Ryan Butterworth Ryan Butterworth - 6 months ago 15
Javascript Question

Setting anchor target dynamically

I am using a WordPress theme that includes a widget for adding social media links into your sidebars/headers etc.

All of the social links are wrapped in a div with a unique class,

social-links
.

I would like to add
target="_blank"
to ALL of the anchors inside the
social-links
div.

So basically,
<a href="facebook.com">Facebook</a>
would change to
<a href="facebook.com" target="_blank">Facebook</a>
, providing that the
social-links
div was it's parent.

Let's say for this instance I don't have time to search around in thousands of lines of code to find where the social media links are being created for the widget, how would I go about dynamically adding the attribute with a class selector in jQuery?

I can use the code below to set attributes directly by using their class or id, but the links don't have unique classes.

$(document).ready(function() {
$(".class").attr("target", "_blank"); //here I need a way to select all anchors that have the .social-links div as a parent
});


And here's an example of the HTML for reference:

<div class="social-links">
<a href="http://www.facebook.com/">Facebook</a>
<a href="http://www.twitter.com/">Twitter</a>
<a href="http://www.youtube.com/">YouTube</a>
</div>


UPDATE: I also just found
$( ".class" ).children()
, but this would apply the attribute to all children inside
.class
, where as I only want to apply it to anchors. How can I also select via tag? Or is there a better/more efficient way?

Answer

To add target="_blank" to all anchors inside the .social-links div you can use .each() and .attr() methods:

$(".social-links a").each(function() { // use $.each to loop through all a tags inside div
   $(this).attr("target","_blank"); // use .attr() to add attribute
});
Comments