BahaaZidan BahaaZidan - 29 days ago 12
jQuery Question

how to append a new hyperlink with a new id each time in a loop?

It's my second day on this project :\

I'm trying to create is : creating a new

<a>
element with a new
href
and
id
attributes in
for
loop so that I can get each output of the API as a link.

This is my JS Code

var one;
var two;
var hoba;

$(document).ready(function() {
$("#inp").keyup(function() {
hoba = $(this).val();
});

$("#but").on("click", function() {
var app = "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=revisions&list=search&titles=Main+Page&rvprop=content&origin=*&srsearch=" + hoba;

$.getJSON(app, function(data) {
for (i = 0; i < data.query.search.length; i++) {
console.log(app);
one = $("<a></a>").text(data.query.search[i].title);

//var _href = $("a").attr("href");
$("a").attr("href", 'https://www.wikipedia.org/wiki/' + data.query.search[i].title);
$("a").attr("id", data.query.search[i].title);

two = document.createElement("p");
two.innerHTML = data.query.search[i].snippet;
$("body").append(one, two);
}
});
});
});

Answer

Use same object to set attributes

one = $("<a></a>");
one.text(data.query.search[i].title);
one.attr("href", 'https://www.wikipedia.org/wiki/' + data.query.search[i].title);
one.attr("id", data.query.search[i].title); 

Use jQuery( html, attributes ) to create HTML element.

var anchor = $("<a></a>", {
    "text": data.query.search[i].title,
    "href": 'https://www.wikipedia.org/wiki/' + data.query.search[i].title,
    "id": data.query.search[i].title
});

$("body").append(anchor);

$(document).ready(function() {
  $("#inp").keyup(function() {
    hoba = $(this).val();
  });

  $("#but").on("click", function() {

    var app = "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=revisions&list=search&titles=Main+Page&rvprop=content&origin=*&srsearch=" + hoba;

    $.getJSON(app, function(data) {
      for (i = 0; i < data.query.search.length; i++) {
        var anchor = $("<a></a>", {
          "text": data.query.search[i].title,
          "href": 'https://www.wikipedia.org/wiki/' + data.query.search[i].title,
          "id": data.query.search[i].title
        });

        var p = $("<p></p>", {
          "html": data.query.search[i].snippet
        });

        $("body").append(anchor);
        $("body").append(p);
      }
    });
  });
});