Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding .className to object is not working

I am attempting to set a className to my nav element and it isn't working as intended. When I manually add the class to my HTML it puts a border around the unordered list items and the buttons. When I use js to add it, it shows that the nav tag has the attribute in the inspector but it does not add the border so I do not believe it is working. What am I doing wrong? I have linked to the bootstrap cdn and jquery cdn in the file.

HTML
<!doctype html>
  <html lang="en-us">
    <head>
      <title>Exercise 5.9</title>
      <meta charset="UTF-8">
      <meta equiv="X-UA-Compatible" content="IE=Edge">
    </head>
    <body id="content">
    <!-- Latest compiled and minified CSS -->
    <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
    <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <nav>
      <div>
        <ul>
          <li>Home</li>
          <li>Our Policies</li>
          <li>How you can help</li>
          <li>What we have accomplished</li>
          <button type="button">Donate $10.00</button>
          <button type="button">Donate $50.00</button>
          <button type="button">Donate $100.00</button>
        </ul>
      </div>
    </nav>
        <p>If you would to offer financial support, please choose the buttons above</p>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
        <script src="exercise-5.9.js"></script>
  </body>
</html>

JS
var nav = document.getElementsByTagName("nav");
nav.className = "navbar navbar-default";
console.log(nav);
like image 223
Mike Avatar asked Sep 03 '15 00:09

Mike


2 Answers

Instead of using .className = try just setting the attribute of class to whatever you want. The main reason why it's not working, however, is because .getElementsByTagName() returns an array (nodeList) so you need to make sure when you set the class, it's properly indexed.

Using .setAttribute("atr", "value")

var button = document.getElementById("btnGo");

button.onclick = function () {
    var nav = document.getElementsByTagName("nav");

    for (var i = 0; i < nav.length; i++) {
        nav[i].setAttribute("class", "myClassName");
    }

};

Using .className

var button = document.getElementById("btnGo");

button.onclick = function () {
    var nav = document.getElementsByTagName("nav");

    for (var i = 0; i < nav.length; i++) {
        nav[i].className = "myClass";
    }

};
like image 107
mwilson Avatar answered Nov 03 '22 17:11

mwilson


getElementsByTagName() return an array, you should write document.getElementsByTagName('nav')[0];

like image 45
Oussama Elgoumri Avatar answered Nov 03 '22 16:11

Oussama Elgoumri