Shubham Shukla Shubham Shukla - 6 months ago 9
Javascript Question

i want to associate links to respective article on dynamically created p element

here is my codepen link

my html code

'<div id="main">
<h1>Wikipedia Viewer</h1>
<form class="form-inline">
<div class="container">
<div class="row">
<div class="col-sm-6 col-sm-offset-4 col-lg-7 col-lg-offset-4">
<div class="form-group">
<label class="sr-only" for="search">search</label>
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="button" class="btn btn-primary"><i class="fa fa-search"></i></button></form>
</div>
</div>
</div>
<a href="https://en.wikipedia.org/wiki/Special:Random">Surprise me!</a>
</div>
<div id="search">
</search>


jquery code for making wikipedia api search call and then displaying title and overview.i want to associate links to respective article on dynamically created p element

$(document).ready(function() {
$("button").click(function() {
var article = $("input").val();
$.ajax({ //wikipedia api call
url: "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" + article + "&format=json",
dataType: "jsonp",
success: function(data) {

for (var i = 0; i < data.query.search.length; i++) { //displaying titles and snippets accroding to search query. i want to associate link to each dynamically created p element.
var title = data.query.search[i].title;
var snippet = data.query.search[i].snippet;
$("#search").append("<p>" + title + "<br>" + snippet + "</p>");
}
$("#main").attr({
'style': 'display: none'
});
},
error: function() {
$("h1").html("oops");
}
});
});
});

Answer

Change your $("#search").append() as follows:

$("#search")
  .append("<p><a href='https://en.wikipedia.org/wiki/" + title + "'>" + title + "</a>" + 
          "<br>" + snippet + "</p>"
         );

Codepen