-2

I have a link like this:

<a href="mypage.php?x=123456"></a>

I need a javascript code to click this link on page load, but since the code generated after "?" is random , i need the script clicking the url starting with "mypage.php" .

How do i achieve this? Thank you in advance

Tony33
  • 147
  • 1
  • 13

3 Answers3

1

You have the "starts with" selector ^=

$( "a[href^='mypage.php']" ).on( "click", function(){
    //do smething
} );

edit

Oh, i got your point. This is what you need.

$( "a[href^='mypage.php']" ).trigger( "click" );

edit2

i've figured out that you may have no jQuery in page. So, here is a fiddle with the propper solution: https://jsfiddle.net/shhzncw1/1/

And here is your script:

(function(){
    var el = document.querySelector('a[href^="mypage.php"]');
    var evt;
    if (document.createEvent) {
        evt = document.createEvent("MouseEvents");
        evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    }
    (evt) ? el.dispatchEvent(evt) : (el.click && el.click());
})();

edit 3

But if your intent is just to go to the page, you could just do a redirect. Think about it. (:

(function(){
    var el = document.querySelector('a[href^="mypage.php"]');
    var href = el.href;
    window.location.href = href;
})();
Filipe Merker
  • 2,428
  • 1
  • 25
  • 41
0

Jquery:

$(document).ready(function(){
        window.location = $('#myanchor').attr('href');
    });

HTML

<a href="mypage.php?123456" id="myanchor"></a>

Check this post --> jQuery: how to trigger anchor link's click event

Community
  • 1
  • 1
Theunis
  • 238
  • 1
  • 15
0

You can try these :-

$(document).ready(function(){
        window.location = $("a[href^='mypage.php']").attr('href');
});
Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
Harsh Sanghani
  • 1,666
  • 1
  • 14
  • 32