john1717 john1717 - 7 months ago 39
Javascript Question

Get the next element of an Anchor

How can I change the value of the next element(td) by searching anchor tag

I have this html code

<TR>
<TD>
<DIV align=center>4</DIV>
</TD>
<TD>
<DIV align=left>
<A href="sample.asp?list=1&amp;vote=1">Juan Dela Cruz</A>
</DIV>
</TD>
<TD>25</TD>
</TR>


and I have this javascript

<SCRIPT>
setTimeout(function() {
var searchString = 'Juan Dela Cruz';
var elements = document.getElementsByTagName('a');
for (var i = 0; i < elements.length; i++)
if (elements[i].innerHTML.indexOf(searchString) !== -1)
elements[i].nextSibling.innerHTML = getRandomInt(200,250);
}, 200);


function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
</SCRIPT>


Then, I want to search thru list of anchors(a) tag with name 'Juan Dela Cruz' .. Then use it to get its next element .. so that I can change the value 25 inside td tag

Searching anchor tag with that name works perfectly , I only have a problem in getting the next element...
I got an error in .nextSibling .. can someone help me fix this code?? thanks :)

Answer

You can try this snippets:

Main thing is you need to care about closest() to get the next td sibling. This closest("td") will return your nearest parent td element. From there you can get your next td element using next("td").

Fiddle Demo

$(function() {
  setTimeout(function() {
    var searchString = 'Juan Dela Cruz';
    $("a").each(function() {
      if ($(this).text() == searchString) {
        $(this).closest("td").next("td")[0].innerHTML = getRandomInt(200, 250);
      }
    })
  }, 200);

  function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<table>
  <TR>
    <TD>
      <DIV align=center>4</DIV>
    </TD>
    <TD>
      <DIV align=left>
        <A href="sample.asp?list=1&amp;vote=1">Juan Dela Cruz</A>
      </DIV>
    </TD>
    <TD>25</TD>
  </TR>
</table>