an alternative way to append child to current tag
We would choose this logic when appending element in pure javascript:
1
2//locate parent tag.
const parent_tag = document.getElementById('div_tag');
1
2
3
4
5// create your child tag.
child_tag = document.createElement('a');
child_tag.textContent="My Site";
child_tag.setAttribute('href', `http://www.yourdomain.com`);
child_tag.setAttribute('target', "_blank");
1
2//append it!
parent_tag.appendChild(child_tag);
Phew, a lot of keystrokes! However, these steps only accomplish this:
Before:
1 | <div id='div_tag'> |
After:
1 | <div id='div_tag'> |
Well, this could drive you mad when you add just a simple feature like this.
So why don’t we just put html template into js function? Though html as a string would frustrate us without syntax highlighting. But this is the trade-off between them.
Meet an alternative function:
1 | element.insertAdjacentHTML(position, text); |
So we can achieve the same result by using a single function:
1 | parent_tag.insertAdjacentHTML('beforeend', '<a href='http://www.yourdomain.com' target='_blank'>My Site</a>'); |
reference:
click this