0

I'm automating some things on a website. I need to check if a "Next" button is there on a page and then click on it. This is the HTML.

<a  href="javascript:goToPage(2);"><span class="txt_purple"></span><img align="absmiddle" src="/icon_next.jpg"  border="0" /></a>

I can use getElementsByTagName('img') to find the image and then how do I do the click?

UPDATED WITH ANSWER:

Adding an id isn't possible in this case. I don't have control over the webpages. It is somebody else's site so I have to do with what's already there. This is what I did:

  var e = document.getElementsByTagName('img');
    for (var i = 0; i < e.length; i++) {
    if (e[i].hasAttribute('src') && e[i].getAttribute('src') == '/icon_next.jpg') {
      e[i].click();
      break;
    }
Crypto
  • 1,217
  • 3
  • 17
  • 33

3 Answers3

2

EDIT

Add an id to your image id=next

<a  href="javascript:goToPage(2);">
    <span class="txt_purple"></span>
    <img id="next" align="absmiddle" src="/icon_next.jpg"  border="0" />
</a>

Then use

document.getElementById("next").click()
Merlin
  • 4,907
  • 2
  • 33
  • 51
  • That's not what I asked. I'm not looking for an onClick handler. I'm looking to trigger a click. – Crypto Jan 10 '14 at 23:34
0

Since you can find the image, you can automate a click by using:

document.getElementById('iwanttoclickthis').click();
JerryHuang.me
  • 1,790
  • 1
  • 11
  • 21
0

"I need to check if a "Next" button is there on a page"

If you want to find out if an element exists:

if(document.getElementById("someID")){

"and then click on it"

Edit 1

See this fiddle - the click event is raised on page load. You can also click directly on the <a>

There is a bit more to this than you might think, because you are trying to invoke click of an <a>. These are not guaranteed to have a click event handler. See this answer. You need something like:

var elem = document.getElementById('myNext');
if( elem )
{
    var event = document.createEvent("MouseEvents");
    event.initEvent("click", true, false);
    elem.dispatchEvent(event);
}

However, it is a bit of a hack. You probably just want to define the onclick directly on the a and call the function.

Edit 2

What you probably really want is to define the onclick on the a href itself. See this updated fiddle. The function is fired on page load as well as if you click the a passing in the element in each case.

HTML:

<a  id="myNext" href="#" onclick="clickAction(this)">
    <span class="txt_purple"></span>
    <img align="absmiddle" src="<yoursource>"  border="0"/>
</a>

Then call the function appropriately:

function clickAction(element)
{
    alert(element);
}

var elem = document.getElementById('myNext');
if( elem )
{
    clickAction(elem);
}
Community
  • 1
  • 1
acarlon
  • 16,764
  • 7
  • 75
  • 94