Reputation: 14918
I made two alert messages using Bootstrap 3. Each alert is a div with class alert.
I'd like to add fade and in classes to each alert so that they fades when closing.
Why does the JS script below not work? Thank you.
var alerts = document.getElementsByClassName("alert");
for (var i = 0; i < alerts.length; i++) {
alerts[i].className += "fade in";
}
I tried using jQuery and that worked.
$(document).ready(function() {
$('.alert').addClass('fade in');
});
Faulty code:
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script type="text/javascript">
var alerts = document.getElementsByClassName("alert");
for (var i = 0; i < alerts.length; i++) {
alerts[i].className += "fade in";
}
</script>
</head>
<body>
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
Message</div>
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
Message</div>
</body>
</html>
Upvotes: 2
Views: 1463
Reputation: 36642
You need to place your script after the elements. You also need a space when adding your new classes alerts[i].className += " fade in";
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
</head>
<body>
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
Message</div>
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
Message</div>
<script type="text/javascript">
var alerts = document.getElementsByClassName("alert");
for (var i = 0; i < alerts.length; i++) {
alerts[i].className += " fade in";
}
</script>
</body>
</html>
Upvotes: 1
Reputation: 318182
Because it already has a class, alert
, and then you add more by just concatenating to the string
"alert" + "fade in" === "alertfade in";
note that you're not getting a space in there, and you could either do
alerts[i].className += " fade in";
which isn't a very good solution, or in modern browsers you can do
alerts[i].classList.add('fade');
alerts[i].classList.add('in');
Or write your function that does somewhat the same, there's a polyfill on MDN that would do that for you.
Also note that you're trying to access the elements before they are available in the DOM, you either need to move the script tag or use a DOM ready handler, but most of all you need to open the console when something doesn't work.
Upvotes: 3