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

Removing nth-Child using a variable from input.

My code sample is as follows

const addItemInput = document.querySelector('input.addItemInput');
const removeItemButton = document.querySelector('button.removeItemButton');


removeItemButton.addEventListener('click', ()=> {
let ul = document.getElementsByTagName('ul')[0];
let nth-Child = addItemInput.value;
let li  = document.querySelector('li:nth-child(#{nth-Child}n)');
ul.removeChild(li);
addItemInput.value='';

});

This is more or less the same as the instructors' aside from the added 'nth-child' variable. My problem is that I cannot remove the nth-child based on this variable. Console reports that this is an invalid selector. Using li:last-child works fine.

I happened to allocate the same input box to add and remove list items.

1 Answer

Steven Parker
Steven Parker
243,318 Points

It looks like you were trying to create a template string, but you have a few issues:

  • variable names cannot contain hyphens
  • template strings must be enclosed in accents ("back-ticks") instead of apostrophes ("single quotes")
  • template placeholders must begin with a dollar-sign ("$") instead of a pound-sign ("#")

So after correction, what you intended would probably look more like this:

let nthChild = addItemInput.value;
let li = document.querySelector(`li:nth-child(${nthChild}n)`);

That solved the issue thank you.