5

Say you wanted to make an element blue with JS, like this:

<p onload="this.style.color = 'blue'">Boy, I sure do wish I was blue</p>

The above line doesn't work, as this targets the window object in that context. You could use ID's, but I'd assume there's a better way.

So, like the title says, is there any easy way to target an element with onload within that onload? Note that such a solution would have to work when there are multiple elements with the onload attribute in the page.

Bunny
  • 192
  • 1
  • 1
  • 14
  • `onload` only makes sense on the `body` tag. But you can make it work with a little more code. – dfsq May 15 '16 at 18:48

3 Answers3

1

You'd have to do it with JavaScript.

You might want to exclude window and iframe elements, but this should get you started.

// Get the list of elements with an `onload` attribute
var list = document.querySelectorAll("[onload]");

// Loop through those  elements
for(var i = 0; i < list.length; i++) {
  var el = list[i];

  // Get the value of `onload`
  var v = el.getAttribute("onload");
  console.log(v);

  // Once you have `v` you need to call it... with something like:
  var func = new Function(v);
  func.call(v);  // This should set `this` properly.
}
Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74
0

Unfortunately the onload attribute will only load on body or iframe elements, not on arbitrary elements.

0

I suggest you send "this" to a function, that will then do what you want with the element.

function change(e){ e.style.color = 'blue'; }

<p onload="change(this);">Boy, I sure do wish I was blue</p>

Although is not the perfect answer or solution, it worked very well for me. Note that I don't know if this will work on every browser though.