Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any easy way to target an element with onload within that onload?

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.

like image 634
Code M4aster Avatar asked Nov 09 '22 15:11

Code M4aster


1 Answers

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.
}
like image 96
Jeremy J Starcher Avatar answered Nov 14 '22 22:11

Jeremy J Starcher