|CreateElement and setAttribute at same time?|
Is there syntax for doing both these operations in a single line of code?
| 2:42 am on Apr 17, 2013 (gmt 0)|
This is admittedly trivial, but it seems in theory that it would be possible. Consider this code:
var myscript = document.createElement("script");
Is there a way to concatenate both of these operations into a single "statement," like this:
var myscript = (document.createElement("script")).setAttribute("src", url);
This doesn't work of course, with or without the added parentheses, but I'm thinking there must be a way to do it.
| 3:45 am on Apr 17, 2013 (gmt 0)|
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:
(myscript = document.createElement("script")).setAttribute("src", url);
You couldn't chain additional methods, though, since setAttribute has no return value.
| 1:33 pm on Apr 17, 2013 (gmt 0)|
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.
| 12:06 am on Apr 18, 2013 (gmt 0)|
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.
| 1:02 am on Apr 18, 2013 (gmt 0)|
Glad to help. :)