0

I have tried using arguments to match case, etc. but have only been returned "null" results at line "document.getElementById(targetId).scrollIntoView();"

Trying to find "FooText" in <p> elements then scroll to parent div.

I have linked the script at the bottom of HTML body, so I think the DOM is ready when the function runs.

HTML

<table width="100%" cellspacing="0" cellpadding="2" border="0" class="bti_resultstable" >
<tr align="left">
<td width="100%" colspan="4">
<div class="bti_racetitle"><p>FooText</p>&nbsp;&nbsp;&nbsp;0 of 0 Precincts Reporting</div>
</td>
</tr>
<tr>
<td width="50%" class="bti_resultcell" border="0" >FooText2 </td>
<td width="20%" align="right" class="bti_resultcell" >0</td>
<td width="20%" align="right" class="bti_resultcell" >0%</td>
<td width="10%" align="center" class="bti_resultcell">&nbsp;</td>
</tr>

<tr>
<td width="50%" class="bti_resultcell" border="0" >FooText2</td>
<td width="20%" align="right" class="bti_resultcell" >0</td>
<td width="20%" align="right" class="bti_resultcell" >0%</td>
<td width="10%" align="center" class="bti_resultcell">&nbsp;</td>
</tr>
</table>

javascript

function search() {
 
    var name = document.getElementById("searchForm").elements["searchItem"].value;
    var pattern = name;
    var targetId = "";
  
    var divs = document.getElementsByClassName("bti_racetitle");
    for (var i = 0; i < divs.length; i++) {
       var para = divs[i].getElementsByTagName("p");
       var index = para[0].innerText.indexOf(pattern);
       if (index != -1) {
          targetId = divs[i].parentElement.id;
          document.getElementById(targetId).scrollIntoView();
          break;
       }
    }  
 };
wilhelmb
  • 1
  • 3
  • Please add your HTML to your question and make sure that your `search()` function isn't being called prior to all the HTML being parsed into memory. – Scott Marcus Jun 28 '22 at 17:37
  • Also, [don't use `getElementsByClassName`](https://stackoverflow.com/questions/54952088/how-to-modify-style-to-html-elements-styled-externally-with-css-using-js/54952474#54952474) or `getElementsByTagName()`. Especially within the context of a loop. Use `querySelectorAll()` instead. – Scott Marcus Jun 28 '22 at 17:38
  • `divs[i].parentElement` has no `id` so `targetId` is `undefined` which causes `getElementById(targetId)` to return `null`. – Besworks Jul 04 '22 at 20:27

0 Answers0