Search code examples
javascriptgetelementbyid

Get Last <a> tag in element with javascript


Consider the following html

<p id="PgLnks">
<a></a>
<a></a>
<a></a>
<a></a>
<a></a>
<P></P>
<P></P>
</p>

How can I get the latest tag from the

tag that Id is PgLnks?

i tried this but not worked

document.getElementsById('PgLnks').querySelectorAll('a:last-child').outerHTML;

Solution

    1. Use getElementById not getElementsById
    2. Use index as .querySelectorAll('a:last-child')[0] then .outerHTML
    3. Also your HTML is invalid as p element may not contain other block elements. So when you will check rendered html you will see total four p tags, what happened was when second p starts it will auto close existing p tag.

    Try with document.getElementById('PgLnks').querySelectorAll('a:last-child')[0].outerHTML

    let lastA = document.getElementById('PgLnks').querySelectorAll('a:last-child')[0].outerHTML;
    console.log(lastA)
    <p id="PgLnks">
      <a></a>
      <a></a>
      <a></a>
      <a></a>
      <a>sss</a>
      <P></P>
      <P></P>
    </p>


    If you can not use <%= PgLnks.ClientID %>, you can try attribute selector as querySelectorAll('[id$=PgLnks]') instead of getElementById('PgLnks').

    • [attr^=value] : Represents elements with an attribute name of attr whose value is prefixed (preceded) by value.
    • [attr$=value] : Represents elements with an attribute name of attr whose value is suffixed (followed) by value.
    • [attr*=value] : Represents elements with an attribute name of attr whose value contains at least one occurrence of value within the string.

    let lastA = document.querySelectorAll('[id$=PgLnks]')[0].querySelectorAll('a:last-child')[0].outerHTML;
    console.log(lastA)
    <p id="ctl13_ctl00_PgLnks" style="color: #0066ff;" align="center">
    
    ۶۷۳ رکورد پیدا شد | در زمان ۳۵ میلی ثانیه | نمایش در ۱۲ صفحه 
    <br>
    &nbsp;
    <a href="/Admin.aspx?mod=Reports&amp;Knd=PersReport&amp;do=Se&amp;FID=2&amp;Page=1">
    <img src="Images/Icons/PgPrev.gif" border="0" title="صفحه قبل" align="absmiddle">
    </a>
    <a href="/Admin.aspx?mod=Reports&amp;Knd=PersReport&amp;do=Se&amp;FID=2&amp;Page=1" style="background-color:#ffffef;padding:3px;border:#a0a0a0 solid 1px;"> &nbsp; ۱ &nbsp; </a>
    <a href="/Admin.aspx?mod=Reports&amp;Knd=PersReport&amp;do=Se&amp;FID=2&amp;Page=3"><img src="Images/Icons/PgNext.gif" border="0" title="صفحه بعد" align="absmiddle"></a></p>