Welcome to WebmasterWorld Guest from 54.166.227.36

Forum Moderators: open

Message Too Old, No Replies

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)

5+ Year Member



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.
3:45 am on Apr 17, 2013 (gmt 0)

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month



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.
1:33 pm on Apr 17, 2013 (gmt 0)

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month



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)

5+ Year Member



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)

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month



Glad to help. :)
 

Featured Threads

Hot Threads This Week

Hot Threads This Month