Metadata Tags
Hopefully you are aware that each page is required to download certain files to use Bootstrap. Pay special attention of what and where each <link>
and <style>
and <script>
tag is in the demo. It is essential that you are totally familiar with external files as well as the inline tags that are not part of the flow (invisible and doesn't affect layout).
HTML/CSS
90% of Bootstrap's layout and behavior is class oriented. You can safely assume that any tag in layout needs a BS class in order to style it. The htmlString provided in OP is void of any class so of course it's not going to appear as expected.
JavaScript
Although commonly used to render htmlString, .innerHTML
has some drawbacks that are commonly overlooked. One major issue is that it rewrites everything within the targeted tag which takes unneeded processing and removal of any attached events. Use .insertAdjacentHTML()
instead -- it doesn't destroy content plus the position in which the htmlString can be determined by the first parameter:
document.querySelector('.navbar').insertAdjacentHTML(position, htmlString)
/**@ Param: [position] "beforebegin" - in front of .navbar as next sibling
"afterbegin" - within .navbar as first child
"beforeend" - within .navbar as last child
"afterend" - behind .navbar as previous sibling
*/
Don't limit yourself with #id, there are other methods that can access a tag by .class, [attribute], and tag as well. Use .querySelector()
to select a single tag by any CSS/jQuery selector.
`<nav id='nav1' class='navbar' name='navigation'></nav>
// by #id
document.querySelector('#nav1')
// by .class
document.querySelector('.navbar')
// by [attribute]
document.querySelector('[name=navigator]')
// by tag
document.querySelector('nav')
In cases of multiple selectors (with the exception of #id in valid HTML), qS()
will get the first one on the page. If you need to target a tag other than the first one you need to do one of the following with qS()
(ex. to access the second nav
tag):
Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> NavBar </title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
<style>
/* extra styles may be added here */
</style>
</head>
<body>
<nav class="navbar navbar-expand-sm bg-dark"></nav>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js'></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>
document.querySelector(".navbar").insertAdjacentHTML('beforeend', `<ul class='navbar-nav'>
<li class="nav-item">
<a class='nav-link' href='index.html'>Home</a>
</li>
<li class="nav-item">
<a class='nav-link' href='about.html'>About</a>
</li>
<li class="nav-item">
<a class='nav-link' href='donate.html'>Donate</a>
</li>
</ul>`);
</script>
</body>
</html>