0

I have a question about adding/removing in HTML.

I have a list, with, say, 3 li. to add one more li I can use either(coach's ) :

const myList = document.querySelector("ul");
const myItem = document.createElement("li");
myList.appendChild(myItem);

or, what I liked more for it's shorten way(tutorial's):

myList.innerHTML += "<li></li>";

but, then, when I wish to remove this added li,(coach's - myItem.remove();) and trying to go the same way as tutorial's, something like:

myList.querySelector(li:last-child).innerHTML -= "<li></li>";

it is not working. apparently it is fundamentally wrong, but nevertheless is there a solution with innerHTML?

appreciate any answer.

1 Answer 1

0

You can't substract a substring from a string, with the - operator. The + has a special meaning here, it is an alias for String.prototype.concat().

Also

myList.querySelector('li:last-child')

returns the <li> element, so you would have to use outerHTML in this case, to target the <li></li> html:

myList.querySelector('li:last-child').outerHTML

If you want to remove the last <li></li> you can use the remove method:

myList.querySelector('li:last-child').remove()

Or assign an empty string to outerHTML:

myList.querySelector('li:last-child').outerHTML = ''

Or you could use any string method to manipulate the string before reassigning it:

let outerHtml = myList.querySelector('li:last-child').outerHTML;
outerHtml = outerHtml.replace('<li></li>', '');
myList.querySelector('li:last-child').outerHTML = outerHtml;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.