How can I extract the text: mytr161 if what is known to me is this text: 8039089332
<tr bgcolor="#dcdcdc" id="mytr161">
<td align="right" bgcolor="#BDB9B4"><input type="checkbox" id="ck161" name="ck161" value="1" onclick="javascript:changebgcolor('161');"></td>
<td align="center" nowrap=""><small><font size="2">
<a href="MfSchOpen850PODetail.asp?lpo=8039089332&litem=hidingit&Plant=hidingitaswell&lsimplifyordertype=hidden" target="Podetail">8039089332</a>
</font></small> </td>
I have a list of numbers like the text: 8039089332. I want to click the checkmark next to it. To do that I am thinking how to write a javascript code to loop through the list of numbers, and click checkmark, I think, firstly need to find the id of the text: 8039089332. And then probably find a way to trim the id by removing the text ‘mytr’ and replacing it by ‘ck’.
This is my first attempt at javascript, I have no idea what to do at this point because I am unable to extract the id for the list of numbers that I have.
3
Answers
You first need to find the element containing the text. You can do this using xPath
Then you can use the function .closest() to get the nearest "parent" that has the characteristic you need (for example in this case we can look for the "tr" element)
Then you can use the .id property to get the Id
You can see a working example below, based on the code you provided (note that I added a table just to make the snipet work, otherwise it would be invalid html)
Note: I did the function to find the element by it’s content based on this SO answer
Since you’re not clicking the checkbox, but want to programmatically "click" them based on the link text
Then, if you want to loop over every a tag, find the text, find the ID…
May want to adjust the for loop instead of document.querySelectAll, maybe target only the table…
Borrowed a lot from https://stackoverflow.com/a/29289196/18392362 plus the "closest(‘tr’)" mentioned above.
Update Since you have a list of numbers you want to find and then check the checkbox: