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) Making Changes to the DOM Getting and Setting Text with textContent and innerHTML

nishnash
nishnash
6,267 Points

innerHTML to add content?

In the Video; he uses innerHTML to add content(<li>red cabbage</li>). However, is there a way to use innerHTML without destroying the previous child elements?

2 Answers

Ioannis Leontiadis
Ioannis Leontiadis
9,828 Points

Hello,

sure, .innerHTML is an elements property and so it can be treated as such. You could append a <li> at the end of an <ul id='list'> using,

let element = document.getElementById('list')
element.innerHTML += '<li></li>'

this is equivalent to,

let element = document.getElementById('list');
element.innerHTML = element.innerHTML + '<li></li>'.

Note that you can also use any JavaScript string manipulation method. For example,

let element = document.getElementById('listContainer');
element.innerHTML = element.innerHTML.replace('ul', 'ol');

will make change the type of the list from unordered to ordered.

Do not forget to take a look at String.replace() combined with the magic of RegExp.

Hope that helped!

nishnash
nishnash
6,267 Points

Hey Loannis, That helped a lot.. thanks for the visuals/explanations :)