Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript and the DOM (Retiring) Traversing the DOM Solution: Using nextElementSibling

O V
O V
2,483 Points

Is there a way to tell which/when methods take an element as a string or as variable?

When doing DOM manipulation, I'm growing confused at when a method takes an element as a string and when as a variable. I would like to know if there is a rule or a way to tell when each happens. I know I can always look at MDN but I was wondering if there is any logical way to tell.

Consider the following:

ul.removeChild( li );  //Here, li is passed as a variable name.

document.createElement( 'li' ); //Here, li is passed as a 'string'.

1 Answer

Steven Parker
Steven Parker
231,269 Points

Most functions that refer to an element will take a reference to the element itself (in a variable) as an argument.

The "createElement" function is somewhat unique in that it makes a new element, so it takes the name of the type (the tag name) that you want to create as a string. The string can either be a literal as shown in the example above, or it could also be in a variable:

var elementType = "li";
document.createElement(elementType); // the argument is still a string

So it's not the variable that makes the difference, it's what the variable represents. When in doubt, look up the function in a reliable reference (I like MDN).