Trying to Learn Javascript Trying to Learn Javascript - 3 months ago 7
jQuery Question

Need help creating unique ID's using a Loop - jQuery

Super new to Jquery.

I'm trying to use jquery to create unique id's for each of my "section" tags by creating a loop. For some reason, this code below is not working, and I'm super confused, so please let me know if you have any ideas what I'm doing wrong.

Also, I'm trying to get my h2 tag inside of my li tag and then get my li tag inside of my ul tag. Any help there would be appreciated as well. All of this information is supposed to be added after my h1 tag.
Thank you

$(document).ready(function() {
var h2 = $("h2");
$(h2).each(function(index) {
for (var index = 0; index < 4; index++) {
$(h2).attr("id", "section" + index);

$(h2).attr("href", "#");
}
});

var ul = $("<ul></ul>").find("ul");
var list = $("<li></li>").find("li");

$(".content h1").append(h2);

});

HTML ADDITION

<body>
<div class="concha">
<h1>The love of my life and how we met </h1>

<h3>The following is information on the Best thing that's ever happened to me</h3>
<h2>We met at the Park</h2>
<p>filler text</p>
<p>filler text</p>

<h2>We went to the movies</h2>
<p>filler text</p>
<p>filler text</p>
<h2>We had ice cream together</h2>
<p>filler text</p>
<p>filler text</p>
<h2>The end</h2>
<p>filler text</p>
<p>filler text</p>

Answer

You are looping through your h2 elements twice. Also, you are writing over all of your h2 elements in your loop. You will need to use this in your loop to call the current element:

$(document).ready(function() {
    var h2 = $("h2");
    var i = 0; // define variable i as your "index"
    $(h2).each(function(index) {
        i++; // Increase i by 1 each time you loop through your h2 elements
        $(this).attr("id", "section" + i); // Use $(this) to pull out the current element

        $(this).attr("href", "#"); // Again, use $(this)
    });

    var ul = $("<ul></ul>").find("ul");
    var list = $("<li></li>").find("li");

    $(".content h1").append(h2);

});
Comments