I’ve written a JavaScript function which does some stuff to the content of another element. For debugging I ran it from onclick, for example:
<span onclick="xyz(this)">abc</span>
Once it was working, I wanted to call it when the page finished loading:
<span onload="xyz(this)">abc<span>
Surprise! It did nothing. The function was never called.
I looked up onload and found that it’s supported by <body>, <frame>, <script>, and a few other tags, but not by <span>.
That kind of makes sense to me, but… now what? Content tags like <span> don’t seem to have any event that is fired when a page is loaded. How can I get that result?
Thank you for trying to answer my question, but it’s not clear to me how that would work. If I put the function call in open code in a <script> block, it’s no longer in the element that the function is supposed to operate on, and xyz(this) becomes meaningless.
I could make the code work by changing the argument from this to something like document.getElementById(“Item_27”), where a bunch of elements in the page are labeled id=“Item_1”, id=“Item_2”,… id=“Item_27”,… but that would a very ugly (and clumsy, and error-prone) solution!
What does your code do to the <span> elements? One option would be to grab a reference to the containing element and then loop over the children, but this only works if all the <span>'s are together in the page. Another option would be to add a class to all the target elements to allow you to select them. Either way, it’s preferable to avoid attaching event handlers directly in your HTML.