homepage Welcome to WebmasterWorld Guest from 54.237.249.10
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Pubcon Platinum Sponsor 2014
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

    
CreateElement and setAttribute at same time?
Is there syntax for doing both these operations in a single line of code?
frobozz




msg:4565469
 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:


<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.

 

Fotiman




msg:4565480
 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:

var myscript;
(myscript = document.createElement("script")).setAttribute("src", url);

You couldn't chain additional methods, though, since setAttribute has no return value.

Fotiman




msg:4565621
 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.

frobozz




msg:4565803
 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.

Fotiman




msg:4565823
 1:02 am on Apr 18, 2013 (gmt 0)

Glad to help. :)

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved