1

So, in my specific case, I am trying to make all the <a> elements in a particular div have the attribute target = "_blank" to open them in new tabs.

But this could work with any element and any attribute. I'm just wondering if there is a way to add these attributes with Javascript.

My first thought was to use CSS, but then I realized that this is not a style issue.

b4ux1t3
  • 439
  • 1
  • 6
  • 21
  • 1
    is jquery an option? – workabyte Aug 22 '14 at 14:56
  • @workabyte Well, yeah. JQuery is just a library for Javascript. But, I suppose I should list that in the tags, too, just in case. – b4ux1t3 Aug 22 '14 at 14:58
  • 2
    ¿pǝᴉɹʇ noʎ ǝʌɐɥ ʇɐɥM – musefan Aug 22 '14 at 14:59
  • FYI, Google delivers many relevant results: https://www.google.com/search?q=javascript%20set%20attribute%20dom – Felix Kling Aug 22 '14 at 15:00
  • @FelixKling TO be honest, it only occurred to me as I was writing this that there was probably a way to do it in Javascript (I hadn't had my coffee yet). But, I figured since I'd already written it out, I may as well stick it on stack overflow so that maybe eventually when people check Google this question (and by extension, the site) will be one of the first few results. Can't fault me for trying to grow the community, can you? :P – b4ux1t3 Aug 22 '14 at 15:07
  • **DUPLICATE**: First Google result for *`"javascript set target"`*... http://stackoverflow.com/questions/804256/how-do-i-add-target-blank-to-a-link-within-a-specified-div – musefan Aug 22 '14 at 15:10
  • @musefan To be fair, the wording of my question is a bit more broad (and therefore more generally applicable). My specific use case is solved by that question (which did not show up for me when I was writing this), but I honestly think that my accepted answer is more concise and my title is more relevant. But, again, I probably wouldn't have asked this question if I'd actually found the one you linked. – b4ux1t3 Aug 22 '14 at 15:13
  • @b4ux1t3: Still, your question `"does not show any research effort"` so I am at a loss as to why it has 3 upvotes – musefan Aug 22 '14 at 15:15
  • @musefan I originally did research into doing this in CSS, and as I mentioned in an earlier comment, it only occurred to me once I had written most of this question that I could probably use Javascript. "Does not show any research effort" to me says "Did not research at all". That is patently untrue. My research was not as thorough as even I would have liked, but it did happen. – b4ux1t3 Aug 22 '14 at 15:17
  • @b4ux1t3: I dunno.. "show" to me means something visible, rather than your word that you did anything at all (not that I am saying you didn't search) – musefan Aug 22 '14 at 15:19

7 Answers7

3

I would not recommand target="_blank" in that case. But you could catch the click event on a link :

var links = document.getElementById('mydiv').getElementsByTagName('a');

for(var i = 0, len = links.length; i < len; i++) {
    links[i].onclick = function(e) {
        e.preventDefault();
        window.location = this.getAttribute("href");
    }
}

Or with jQuery :

$('#mydiv a').click(function(){
    window.location = $(this).attr('href');
    return false;
});
Brewal
  • 8,067
  • 2
  • 24
  • 37
  • I was just about to add a vanilla JS sollution, but then I saw yours. Nice and complete, great that you supplied both vanilla and jQuery! – Dennis Jamin Aug 22 '14 at 15:08
  • I'm going to accept this answer in about a minute, and I wanted note why, considering there have been a bunch of decent answers. You provided me with an approach that thinks outside of my question's box, AND gave more than one method. For curiosity's sake, why is `target="_blank" not recommended? – b4ux1t3 Aug 22 '14 at 15:10
  • hmmm... question = "how to add attributes", accepted answer = don't add any attributes whatsoever – musefan Aug 22 '14 at 15:13
  • Well `target="_blank"` depends on html version... But I rephrased my first sentence... It can be used, but still, `target="_blank"` **and** javascript redirections are often not welcomed since it changes the default navigation behaviour of a browser. That said, @musefan is right, but I couldn't help myself to give an alternative ^^ – Brewal Aug 22 '14 at 15:18
  • @musefan His is the best answer to my particular use case. Anyone who is searching specifically for this use case will get here, see this answer, and use it. Anyone who is looking to add a different attribute will see that this answer is not exactly what they are looking for, scroll down, et voila, adding attributes. The point of this site is not to be a flawless encyclopedia of knowledge, but a place where questions get answered. Arguing semantics is not helping anyone. – b4ux1t3 Aug 22 '14 at 15:20
  • @b4ux1t3: I don't make the rules... I just try to follow them. In my experience, this question got the upvotes because it is so easy to answer so people see it as an opportunity to earn some easy rep (which is why there are so many answers effectively saying the same thing) – musefan Aug 22 '14 at 15:23
  • @musefan It is entirely understandable to follow rules. I get that. But as the general attitude towards lawyers suggests, arguing over the letter of the law without allowing for the spirit of the law leads to a lot of pay and a lot of contempt. I feel that this question fits the spirit, if not the direct wording, of the rules for this site. – b4ux1t3 Aug 22 '14 at 15:26
  • @musefan I'm not here for rep... I just gave this anwser because it was diferent, and I thought that was nice to give another point of view ! But well, there's no problem here :) – Brewal Aug 22 '14 at 15:27
  • 1
    @b4ux1t3: meh, I don't really care either way. I did my bit, it's the choice of the people so it is what it is – musefan Aug 22 '14 at 15:30
  • 1
    @Brewal: I'm not saying you are, and I agree an alternate answer is nice, but all the other answers saying the same thing is just a bit silly in my opinion – musefan Aug 22 '14 at 15:31
2

TRY THIS myElement.setAttribute("yourattribute", "yourvalue");

Benjamin
  • 2,612
  • 2
  • 20
  • 32
2

As workabyte points out, this is probably a job for jQuery...

$("#divId a").attr("target", "_blank");
paul
  • 21,653
  • 1
  • 53
  • 54
2

if you use jQuery then you could do this on load if there is some way to select the div in question.

$(function(){
    $('#divId').find('a').attr('atribute name','value for atribute');
});
workabyte
  • 3,496
  • 2
  • 27
  • 35
1
$('#divId').children('a').attr('attrName','attrVal');
Fueled By Coffee
  • 2,467
  • 7
  • 29
  • 43
1

Get elements by document.getElementsByTagName('a') or similarly and use setAttribute function.

But if you want this behaviour everywhere i'd recommend to set it in html.

sepulchered
  • 814
  • 7
  • 18
1

Here is a small example in pure javascript:

<div id="myDiv">
   <a href="http://google.com">Google</a>
   <a href="http://facebook.com">Facebook</a>
</div>
<button onclick="setLinksTarget()">Set target</button>

<script type="text/javascript">
function setLinksTarget(){
    var div = document.getElementById('myDiv'),
        links = div.getElementsByTagName('a'),
        i;

    for(i = 0; i < links.length; i+=1){
        links[i].setAttribute('target', '_blank');
    }
}
</script>

Note that setAttribute is not supported in IE8 and bellow (according to http://www.w3schools.com/jsref/met_element_setattribute.asp)

You could also use jquery to do the job and then it's a one liner:

function setLinksTarget(){
    $('#myDiv a').attr('target','_blank');
}
Denis Shulepov
  • 381
  • 1
  • 6