This is a defining problem because global evaluation does not invoke code in the same scope as the element variable. If you must use eval , although eval is evil , you will have to do it so that you can call your code in the right environment. One way to do this is to wrap it as an anonymous function that you give parameters to the selected environment variables.
for instance
window.eval.call(window,'(function (element) {'+src+'})')(element);
This means that the src string is parsed but not called eval , as it returns an anonymous function. Then you call it passing your data, in this case element .
Test it with var element = document.body, src = 'console.log(element.tagName)'; and you will see its log "BODY" . Note that if you want to set global variables (or functions) this way, they must be specified as global explicitly ( window.foobar = ... ), or they will be GCd after the completion of the anonymous function.
source share