0

I'm attempting to add target="_blank" to an a tag that I've wrapped around an ID for a column containing a number of elements.

I've tried adding the attribute target="blank", but it doesn't appear to be working.

Here is the column I've wrapped with an a tag.

<div id="loyaltycol1"> This is some text. <img src="#" alt="A Picture" /> </div> 

Here is the javascript code.

jQuery(function($) { $("#loyaltycol1").wrap("<a href='www.examplesite.com'></a>").attr('target','_blank'); }); 

How can I get the a tag to have target="_blank"?

5
  • 4
    Firstly it's #loyaltycol1, not #loyatycol1 (missing 'l'). Secondly, wrap returns the original #loyaltycol1 element, not the a, so you're adding the attribute to the wrong element. Use .parent().attr(.... That being said, if you're hard-coding the a anyway, just add the attribute in the HTML string. Commented Aug 27, 2019 at 16:25
  • That was just a typo on my part. It's correct in the site. I'll update it above. I'm not hard coding. I'm trying to add this element to an existing framework that will be maintained by a client, so I'd like to not build out custom coded elements if possible. Sorry, I don't understand what you are suggesting here. Are you saying to do: jQuery(function($) { .parent(#loyaltycol1).attr('target','blank'); }); Where would the wrap for the a tag come in? Commented Aug 27, 2019 at 16:33
  • .wrap("<a>").parent().attr(... Commented Aug 27, 2019 at 16:43
  • "so I'd like to not build out custom coded elements if possible". You aleady are. <a href='...'></a> is a custom coded element. As Rory pointed out, if you want the target attribute on that link, just add it to that string. Don't try to force it to be a second operation. Commented Aug 27, 2019 at 16:55
  • Yes I already did that but it broke my code. Just figured out what I did wrong. I added target="_blank" rather than target='_blank'. The former broke my jquery which is why I thought it wasn't an option. Commented Aug 27, 2019 at 17:45

1 Answer 1

1

You're trying to add the attribute onto the div instead of the anchor tag. There's multiple ways you can solve this but here's one where you create the anchor with the target attribute

jQuery(function($) { $("#loyatycol1").wrap( $("<a href='www.examplesite.com'></a>").attr('target','_blank') ) }); 

https://jsfiddle.net/1v043km6/

Or just adding it to the string

jQuery(function($) { $("#loyatycol1").wrap("<a href='www.examplesite.com' target='_blank'></a>"); }); 

https://jsfiddle.net/0v5g9dbr/

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.