Welcome to WebmasterWorld Guest from 220.127.116.11 , register , free tools , login , search , pro membership , help , library , announcements , recent posts , open posts Pubcon Gold Sponsor 2015!
CreateElement and setAttribute at same time? Is there syntax for doing both these operations in a single line of code? frobozz
This is admittedly trivial, but it seems in theory that it would be possible. Consider this code: <script> var myscript = document.createElement("script"); myscript.setAttribute("src", url); </script> Is there a way to concatenate both of these operations into a single "statement," like this: <script> var myscript = (document.createElement("script")).setAttribute("src", url); </script> This doesn't work of course, with or without the added parentheses, but I'm thinking there must be a way to do it.
createElement returns an Element. setAttribute does not have a return value. I don't think there's much value in doing it, but you could do something like this: var myscript; (myscript = document.createElement("script")).setAttribute("src", url); You couldn't chain additional methods, though, since setAttribute has no return value. Fotiman
Note, jQuery (for example) handles this by always returning a jQuery object (which has all of the methods available). But because the DOM method setAttribute doesn't return a value, you'll never be able to chain that and then try to assign the result to a variable. frobozz
Fotiman, thanks for your helpful reply. You're right, there isn't much benefit in doing it, but at least I understand now how it could be done. Fotiman
Glad to help. :)