Dalton Edwards
Dalton Edwards

Reputation: 45

How do I loop through HTML elements and JSON with jQuery?

I'm trying to loop through all elements with the class name steem_verify, and then append " Verified" after the usernames who are verified according to my API. I finally got it working (kind of), but after verified names it says " Verified Verified Verified", so I'm guessing my loop is messed up somewhere.

Here's my code:

$.getJSON("https://steemverify.com/api/verified.json", function (data) {
    $.each(data, function (i, item) {
        $(".steem_verify").each(function (index) {
            var username = $(this).text();
            $(data).each(function () {
                if (item.username == username) {
                    $(".steem_verify")[index].append(" Verified");
                }
            });
        });
    });
});

Upvotes: 0

Views: 72

Answers (2)

Cœur
Cœur

Reputation: 38667

Solution by OP.

This code works:

$.getJSON("https://steemverify.com/api/verified.json", function (data) {
    $.each(data, function (i, item) {
        $(".steem_verify").each(function (index) {
            var username = $(this).text();
            if (item.username === username) {
                $(".steem_verify")[index].append(" Verified");
            }
        });
    });
});

Upvotes: 1

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

simply no need for first loop

$.getJSON("https://steemverify.com/api/verified.json", function (data) {
    //$.each(data, function (i, item) {
        //alert(item.username);
        $(".steem_verify").each(function (index) {
            var username = $(this).text();
            $(data).each(function ( i , item) {
                if (item.username == username) {
                    $(".steem_verify")[index].append(" Verified");
                }
            });
        });
    //});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="steem_verify">dalt</div>
<div class="steem_verify">steemitqa</div>
<div class="steem_verify">steemverify</div>

in another way you need just one loop and use .filter() so your code will looks simple like this

$.getJSON("https://steemverify.com/api/verified.json", function (data) {
   $.each(data, function (i, item) {
       $(".steem_verify").filter(function(){return item.username == $(this).text() }).append(" Verified");
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="steem_verify">dalt</div>
<div class="steem_verify">steemitqa</div>
<div class="steem_verify">steemverify</div>

Upvotes: 1

Related Questions