Reputation: 13
What I am trying to do is add an id to my dynamic info. This line
var webaddress = '<img id= "[index]" src="http://pokeapi.co/media/img/[index].png">';
If I take out the id="[index]
the loop works fine and gives me the images. But i need to add an id to all of them so i can do other stuff. Bonus help would be nice if someone could tell me how to change the docuent.write(text) to write to a specfice div so i can put my script at top of page.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
</style>
<script type="text/javascript" rel="script" type="script" href="script.jss"></script>
<script type="text/javascript" src='http://code.jquery.com/jquery-1.10.2.min.js'></script>
<script type="text/javascript">
$(document).ready(function() {
});
</script>
</head>
<body>
<div id="wrapper">
</div>
<div id="pokedeck">
<div id="pokelist">
<script type="text/javascript">
var webaddress = '<img id= "[index]" src="http://pokeapi.co/media/img/[index].png">';
var text = "";
for (var i = 1; i <= 152; i++) {
text += webaddress.replace("[index]", i);
}
document.write(text);
</script>
</div>
<div id="deck1"></div>
</div>
Upvotes: 0
Views: 66
Reputation: 58462
Square brackets are special characters so you need to escape them. See the code below (I have added comments to it)
// the following goes in your document ready
var webaddress = '<img id= "[index]" src="http://pokeapi.co/media/img/[index].png">';
var pokelist = $('#pokelist'); // get your pokelist
for (var i = 1; i <= 152; i++) {
var image = webaddress.replace(/\[index\]/g, i); // escape your square brackets and make it a global replace - anything inside the / / is replaced and the g means all occurences of
pokelist.append(image); // append it to your div
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
</div>
<div id="pokedeck">
<div id="pokelist">
</div>
<div id="deck1"></div>
</div>
I would also move your scripts to just before the closing body tag rather than have them in the header
Upvotes: 2