Search code examples
javascriptjqueryeachcontainswindow.open

Can I get all hyperlinks that contain "@" then open them in new tabs?


I'm trying to open all hyperlinks on a page with link text that includes the "@" symbol.

Here's an example below

[[email protected]](https://stackoverflow.com/2342342352) 
[[email protected]](https://stackoverflow.com/2342525233423)
[[email protected]](https://stackoverflow.com/23943234)

So far, I can collect each of the lines that include an @ symbol with this jQuery selector:

$("a:contains('@')")

This gives me a list of every anchor tag that has @ in the link text, it looks like this:

jQuery.fn.init {0: a, 1:a, 2:a,}

For a cleaner array, I used

$("a:contains('@')").get

Which returns

(3) [a, a, a]

I tried using this for loop to click every a tag in the array but as soon as I click the first one, it stops.

var mapps = $("a:contains('@')").get()

for (var i = 0, len = mapps.length; i < len; i++) {
  mapps[i].click();
}

So to open multiple links in new tabs, I'm going to try using window.open() which I believe requires the URL.

I can extract the URL in the first anchor tag by using this code:

$("a:contains('@')").prop('href');

However, .prop only returns the first URL.

Is there a way for me to return all URLs then feed them into a for loop and open them in new tabs?

I'm trying to figure this out with .each() but it's been very difficult for me. Please let me know if you need more context and forgive my lack of experience.


Solution

  • You can use the each and $(this).prop('href')

    $("a:contains('@')").each(function() {
      window.open($(this).prop('href'), '_blank');
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    
    <a href="https://stackoverflow.com/2342342352">[email protected]</a>
    <a href="https://stackoverflow.com/2342525233423">[email protected]</a>
    <a href="https://stackoverflow.com/23943234">[email protected]</a>