Home > Net >  Target class within footer tag with javascript
Target class within footer tag with javascript

Time:12-21

I'm trying to append some HTML to the end of div within a footer tag like this:

<footer>
 <div >
  <p>Stuff</p>
  <!-- want to insert HTML here -->
 </div>
</footer>

I'm not sure how to target the child class using regular JavaScript. I know I could use jQuery, but that's not available, so I'm trying the vanilla JS way. I know I can use document.querySelector or document.getElementsByTagName, but I'm not sure how to chain them together to use insertAdjacentHTML. For example:

function loadThing() {
var footer = document.querySelector('footer .menu-footer');
footer.insertAdjacentHTML('beforeend', '<p>Stuff to add</p>');
}

window.onload=loadThing();

I know that's not right, but I'm not sure how to get the order correct to append to the child elements

CodePudding user response:

Your insert method is correct, remove parentheses after your function and it will work,, here i mean

  • window.onload=loadThing(); Wrong
  • window.onload=loadThing; Correct

Here you are assigning the result of your loadThing function which is undefined to your load event

CodePudding user response:

Just simply append child inside .menu-footer it will come after p tag element

e.g. `enter code here

var parent = document.querySelector('.menu-footer');

var newElement = document.createElement('div');
    newElement.className = 'childDiv';
    newElement.innerText = 'Inner Div';
    parent.appendChild(newElement);
<footer>
 <div >
  <p>Stuff</p>
  <!-- want to insert HTML here -->
 </div>
</footer>

`

  • Related