
Fail to get img id in javascript
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>
-
Related Reading
- Javascript multidimensional array (create, add and r
- Javascript trim string whitespace, with removing lef
- Remove text after clicking in the textbox and then d
- Javascript get referrer url(previous page url), curr
- Javascript get current url, domain from url, relativ
- Javascript convert hex to decimal, binary to hex, oc
- Javascript delay loading images to improve web page
- Remove html element javascript by their parent or cl
- Javascript split usage and examples, with splitting
- Javascript get all input elements in form and all im
- Javascript sets the element height that cannot be au
- Javascript create element(div,li,img,span) dynamical