Good day. How to attach click events to link number 2, when the first link is dynamic, that is, it appears and disappears randomly.

This script should work with DOM, there is no possibility to work with the code.

<div class="a"> <a class="href" href="#">1</a> //Рандомная ссылка <a class="href" href="#">2</a> <a class="href" href="#">3</a> </div> var el = document.getElementsByClassName('href')[0]; el.click(); 

I would count the number of links. If there are one more links, he fulfilled the if condition, added one to zero. But there are cases when there are much more links, and I need to bind the event to a specific link.

  • nothing is clear - Igor
  • I need to bind the event to a specific link. - and how do you want to determine to which link the event should be tied? - Grundy
  • @ Grundy, I don’t know this. - Sergiyss
  • one
    @Sergiyss, can you specify HTML links? If she has at least some unique parameter, then you can get attached to it. - Alex Zhulin
  • one
    @Sergiyss - it means you need to make it unique by setting it with an additional special class that you can never declare <a class="flhdr selectme" ... - Igor

2 answers 2

If only the name is unique, you can search by name.

 var link = null , links = document.getElementsByTagName('a') , searchText = 'Бить врагов '; for (var i = 0; i < links.length; i++) { if (links[i].textContent === searchText) { link = links[i]; break; } } if (link) { console.log('Ссылка найдена.'); //link.click(); } else { console.log('Ссылка не найдена.'); } 
 <a class="flhdr" href="#">Не бить врагов</a> <a class="flhdr" href="?wicket:interface=:2:actionPanel:damageRandomEnemyLink‌​::ILinkListener::&am‌​p;action=14928018000‌​48"><img class="internalIcon" alt="" src="/images/icons/attack.png" border="0">Бить врагов </a> 

  • Thanks, helped) - Sergiyss
  • And the cycle enumerates all the links completely, until it finds the right name in it, and then enters this link in the link variable? - Sergiyss
  • @Sergiyss, yes, but it is possible to limit the search area, if part of the original HTML was provided more. - Alex Zhulin

Maybe so:

 $('body').on("click", 'a.href', function (e) { //Уточняем элемент });