Scott B
Scott B

Reputation: 40157

jQuery to make all child links of a given div open in a new window

I have a div with ID "MyDiv" in which I need all child anchors of this div to open in a new window.

I'm trying:

jQuery('#MyDiv.children() a').click(function(){
    jQuery(this).attr('target', '_blank');
});

Upvotes: 2

Views: 3137

Answers (4)

scessor
scessor

Reputation: 16115

The problem is the main selector. .children() is not a valid part of a css selector. If you add a space in the css selector, the following part of the selector will be searched in all child nodes. If you want to search in the direct child nodes only, you can use > instead. E.g. replace #MyDiv.children() a with #MyDiv>a:

jQuery('#MyDiv>a').click(function(){
    jQuery(this).attr('target', '_blank');
});

or you can use:

jQuery('#MyDiv>a').click(function(oEvent) {
    oEvent.preventDefault();
    window.open($(this).attr('href'), '_blank');
});

Upvotes: 1

Filip Roséen
Filip Roséen

Reputation: 63797

click here for jsFiddle example

$('#MyDiv a').attr ('target', '_blank');

If you are unsure about how this attributes works read up on it below:


If you don't fancy the use of target="_blank" (it's often frowned upon when writing xHTML) you could bind a click event to the anchors and open a new window using javascript/jquery.

Such as in the below example:

click here for jsFiddle example

$('#MyDiv a').click(function(ev) {
  window.open(this.href);
  ev.preventDefault   (); // see post comment by @nbrooks
});

Upvotes: 2

painotpi
painotpi

Reputation: 6996

you can get rid off the .children() in the selector.

Markup:

<div id="MyDiv">
    <a href="http://wwww.google.com">1</a>
    <a href="http://wwww.google.com">2</a>
    <a href="http://wwww.google.com">3</a>
    <a href="http://wwww.google.com">4</a>
</div>​

jQuery:

$('#MyDiv a').click(function(){ 
    $(this).attr('target', '_blank'); 
}); ​

jsFiddle example

Upvotes: 1

muthu
muthu

Reputation: 5461

This may be useful for you

$('#MyDiv a').live('click', function() {
    window.open($(this).attr('href'));
    return false;
});

Upvotes: 0

Related Questions