Fail to get img id in javascript

Lionsure 2020-06-24 Original by the website

I encountered a strange problem in the process of debugging javascript code. The src attribute value of img can be got normally under Internet Explorer, but it cannot be got under Chrome, FireFox or Safari. After debugging, it is found that the img object cannot be got through document.getElementById. Putting javascript behind the img to be got does not work, indicating that the img is not loaded, depending on the specific situation.

 

1. The specific situation of failing to get img id in javascript

Due to the development needs of the program, the img is output in C# in the background, the code is as follows:

1) html:

<div id="img">
              <asp:Literal ID="litImg" runat="server" />
       </div>

<script type="text/javascript" language="javascript">
              document.getElementById("imgId").src;//Cannot get img object
       </script>

Document.getElementById("imgId").getAttribute("src") doesn't work either.

 

2) Background code(C#):

protected void Page_Load(object sender, EventArgs e)
       {
              //Output img
              litImg.Text = "<a href=\"#\" target=\"_blank\"><img id=\"imgId\" src=\"/images/prod.jpg\" /></a>";
       }

Doubt: If it is not output in the background, but directly write img to the foreground (<img id="imgId" src="/images/prod.jpg" />), you can get it.

 

3) Explain

Put this code in a new aspx file, but you can get the img object and its src. From this point of view, it should be that an unknown element in the original aspx file affected Chrome, FireFox, and Safari to got the img object. Due to the confidentiality of the program, the code cannot be disclosed(there are also many codes).

 

2. Solution

Since the img itself cannot be got directly, you can first get its parent object, and then get it through the parent object, the code is as follows:

<div id="img">
              <asp:Literal ID="litImg" runat="server" />
       </div>

<script type="text/javascript" language="javascript">
              var obj = document.getElementById("img");//Get parent of img
              var src = obj.getElementsByTagName("img")[0].src;//Get img's src
       </script>