JavaScript JavaScript and the DOM Traversing the DOM Solution: Using nextElementSibling

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
195,274 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).