R Ganesh R Ganesh - 21 days ago 8
Ajax Question

need help in linking with wikipedia viewer

when i click the heading i want to go to relevant wikipedia article.i tried the wrap method.But it isn't happening.please help.
Here is the code.

$(function(){
$('#bar').click(function(){
$('#bar').hide().fadeOut(1000);
$('#search_box').show().fadeIn(2000).focus();
$('a,p').hide();
$('.btn').show();
});
$('#clear').click(function(){
$('#search_box').val('');
});
$('#search_box').keypress(function(e){
if(e.which == 13)
{
getData();
}
});

$('#search').click(function(){
getData();
});

function getData()
{
$('.title ,.card').remove();
var searchQuery = $('#search_box').val();
$.getJSON('https://en.wikipedia.org/w/api.php?format=json&action=query&list=search&srsearch='+searchQuery+'&utf8&callback=?', function(data){
console.log(data);
var query = data.query.search;

for(var i=0;i<query.length;i++)
{

**$('<div class="title">'+query[i].title+'</div>').addClass('title').wrap('<a href="http://en.wikipedia.org/wiki/"'+encodeURIComponent(query[i].title)+'"> </a>').appendTo('body');**


$('<div>'+query[i].snippet+'</div>').appendTo('body').addClass('card');;

}

});
}
});


And here is a link to my pen.
http://codepen.io/R_Ganesh/pen/eBBmwW

Answer

You can use .wrapInner() method to wrap link inside div element

$('<div class="title"></div>')
.wrapInner("<a href='http://en.wikipedia.org/wiki/"+encodeURIComponent(query[i].title)+"'>"+query[i].title+"</a>")
.appendTo('body');

in your .wrap() method your link doesn't have any value.

.wrap('<a href="http://en.wikipedia.org/wiki/'+encodeURIComponent(query[i].title)+'"> </a>')
                                                                                     ^

Add query[i].title value to link. And with wrapInner() wrap that link around the <div class="title"> content

Check working code: codePen