0

I would like to insert HTML code to make a "list". I've seen examples of innerHTML but that just replaces the existing code. How can I add more code without replacing the current code?

var addTo = document.querySelector(".activePage")[0];
var addHTML = '
<div id="item1">
  <h1>This is a heading</h1>
  <p>This is a paragraph</p>
</div>'

addTo.innerHTML(addHTML)'
<nav class="activePage"><nav>

4 Answers 4

1

Use insertAdjacentHtml. Docs - https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML.

var addTo = document.querySelector(".activePage");

var addHTML = '<div id="item1"><h1>This is a heading</h1><p>This is a paragraph</p></div>

addTo.insertAdjacentHtml(addHTML, 'beforeEnd')

'beforeEnd' means it will add right before the end of the element(inside the element).

Sign up to request clarification or add additional context in comments.

3 Comments

I'm getting an error, apparently addTo becomes undefined
Edit: It worked after removing the [0] from the end of querySelector, any idea why?
It is because querySelector returns only 1 element, since it worked for you could you upvote and make it the right answer
1

You have to append to the HTML inside the nav tag instead of replace it with a new value.

var addTo = document.querySelector(".activePage");
var addHTML = '<div id="item1"><h1>This is a heading</h1><p>This is a paragraph</p></div>';
addTo.innerHTML += addHTML;
<nav class="activePage">
<nav>

Comments

1

Add your HTML to the existing HTML inside of the target element using +=.

function addNew() {
  var addTo = document.querySelectorAll(".activePage")[0];
  var addHTML = '<div id="item1"><h1>This is a heading</h1><p>This is a paragraph</p></div>'
  addTo.innerHTML += addHTML
}
<nav class="activePage">
  <button onclick="addNew()">add</button>
  <nav>

Comments

0

I believe what you're after is the append feature. https://api.jquery.com/append/ or https://www.w3schools.com/jsref/met_node_appendchild.asp

Below is a jquery example. I have used this example as i think it's easier to understand what's going on at first glance

example:


    $(".your_div").append(html_load());
    
    function html_load() {
       return  '<li class="list"> list item </li>'
    }

This will result in the below:


    <div class="your_div">
        <li>start</li>
    </div>

being updated to:


    <div class="your_div">
        <li>start</li>
        <li class="list"> list item </li>
    </div>

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.