skip to Main Content

I have multiple anchor tag in a page. I want to click all the tag from jQuery to open each link in a new tab. But it is working only for the first element.

My attempt is below:

    $('.tbl a').each(function () {
    var url = $(this).attr("href");
    window.open(url, '_blank');

})

Note: if I set background color in each it works well. Then why not new Tab?

2

Answers


  1. My suggestion from the comments would look something like this :

    Won’t work here, because the sandoxed frame does not allow popups, but you get the idea.

    $('.opener').on('click',function(){
      $('ul a').each(function (index) {
          var url = $(this).attr("href");
          window.open(url, '_blank'+index);
    
      })
    })
    .opener{
      display:inline-block;
      background-color:#ccc;
      cursor:pointer;
      color:#FFF;
     }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <h1>open new tabs</h1>
    
    <p>An unordered list:</p>
    <ul>
      <li><a href="https://www.coffe.com">Coffee</a></li>
      <li><a href="https://www.tea.com">Tea</a></li>
      <li><a href="https://www.milk.com">Milk</a></li>
    </ul>
    
    <p class="opener">test open </p>
    Login or Signup to reply.
  2. Building on the answer in the comments,

    $('.tbl a').each(function () {
      $(this).on("click", function(e){
        window.open(e.target.href, '_blank');
      })
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search