Dardar1991
Dardar1991

Reputation: 37

http javaScript set attribute default to all tags

I am pretty new to HTML and just trying to figure things out...

I am trying to set an attribute for the tag, more specifically the target attribute so that all links in web page would open in a different tab...

I have encountered the jQuery functions and tried to implement it with no success...

My script tag goes like this:

<script src="static/jquery-3.1.1.js">
    $(document).ready(function() {
        $('a').target = "_blank"
        $("a").attr("target", "_blank");
    });

    $('a').target = "_blank"
</script>

when of course the jquery file is at the same directory under static dir as mentioned....

I have also tried the following:

<script>
    var elems = document.body.getElementsByTagName("a")[0];
    elems.setAttribute("target","_blank");
</script>

when there's only one tag in page...

Please tell me what am I doing wrong....

Thanks:)

Upvotes: 1

Views: 2217

Answers (4)

Super User
Super User

Reputation: 9642

You have some syntax error in your script, correct code in

<script src="static/jquery-3.1.1.js"></script>
<script>
    $(document).ready(function() {
        $("a").attr("target", "_blank");
    });
</script> 

Upvotes: 0

jessegavin
jessegavin

Reputation: 75650

You don't actually have to modify the html, you could just add a click handler to every link like so.

$(document).on('click', 'a', function(e) {
  e.preventDefault();
  window.open(this.href);
});

Upvotes: 0

blackmiaool
blackmiaool

Reputation: 5344

At first, your code should be like:

$(document).ready(function() {
    $("a").attr("target", "_blank");
});

It actually works. You can try it on this page. I don't know what page r u testing on, but I can guess the reason why your code didn't work is that some links are generated after the execution of your code. You can change your code as below to avoid this problem.

$(document).ready(function() {
    setInterval(function(){
       $("a").attr("target", "_blank");
    },200);
});

You can also add some code to imporve the efficiency.

Upvotes: 0

Shakti Phartiyal
Shakti Phartiyal

Reputation: 6254

The correct approach to set an attribute to all elements of a web page is to loop through all elements and set the attribute like so:

var elems = document.body.getElementsByTagName("a");
for(var i = 0; i < elems.length; i++)
{
  elems[i].setAttribute("target","_blank");
}

If using jQuery the function to set attributes is $(selector).attr(attribute_name,value)

Example:

$('a').attr("target","_blank");

Upvotes: 1

Related Questions