2

[edit] I am NOT using jquery in this app.

Looking for a way to force preexisting links to open in a new window. But I only want to Apply this behavior to links appearing in a specific div element that has a classname but no ID

4
  • I am NOT using jquery in this app. ... Well, you should. It'll make your life much easier. Commented Mar 11, 2010 at 1:53
  • 2
    It may make life easier but it's not necessary. Commented Mar 11, 2010 at 1:54
  • I never said it's necessary. Similarly, no-one ever said that a bed is necessary. Commented Mar 11, 2010 at 2:01
  • I'm fine with using jquery, depending on the app, but it seems a bit of a stretch to hang it on as an afterthought, just so Its simpler to do this one task. I think for this app, I'd rather just add an ID to the div element, along with FF's solution and call it a day ;) Commented Mar 11, 2010 at 3:38

4 Answers 4

2

If you're not using jQuery, first get the element that you want to apply it to.

var allDivs = document.getElementsByTagName('div');
var myDiv = null;

for (var j = 0; j < allDivs.length; j++) {
    var divClass = allDivs[j].getAttribute('class');
    if (divClass != null && divClass.indexof(THE_CLASS_NAME) >= 0) {
        myDiv = allDivs[i];
        var allAnchors = myDiv.getElementsByTagName('a');
        for (var i = 0; i < allAnchors.length; a++) {
            allAnchors[i].setAttribute('target', '_blank');
        }
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

I think you meant allAnchors[i].
Notice how much simpler the jQuery way is. (This is the simplest cross-browser way to do it without jQuery or a similar library
I'm not saying jQuery is a bad idea I'm just saying that it's not necessary. That also doesn't mean he can't use any other library of his choice, but I'm giving him an answer without dependence on a third party.
@FF > I'm getting Error: divClass.indexof is not a function, changed it to indexOf which resolved that error. Now getting myDiv is undefined ?
1

The simplest way to do this is to use jQuery:

$('div.SomeClass a').attr('target', '_blank');

Comments

1

If you are using jQuery you can do like this:

$(function(){
  $('.ClassNameOfTheDiv a').attr('target', '_blank');
});

Comments

0

Try...

<a href="javascript:window.open('www.yoursite.org')>Your Site Opens in a new window</a>

2 Comments

You're misunderstanding the question.
welcome to SO cymorg, but as SLaks pointed out please try to make sure that you are answering the actual question being asked :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.