I am reading a table row from one page, and then trying to put the cell contents into various elements on a second page. I have it sort of working, but I’d like to (a) do it properly, and (b) get rid of the extra tags I’ve picked up.
So my method is….
$(document).ready(function() {
$(function(){
$('#result_row').load('schedule.html #schedule_list tr:eq(1)',function(){
var date = $('td:eq(0)',this);
$('#date').html(date);
var title = $('td:eq(0)',this);
$('#title').html(title);
var speaker = $('td:eq(0)',this);
$('#speaker').html(speaker);
});
});
});
and then I have
<div class= "upcoming">
Next Talk: <span id="speaker"></span> - <span id="title"></span> (<span id="date"></span>)
</div>
<span id="result_row"></span>
So this works to a point but I have a distinct feeling I’m doing it inefficiently (or wrong) as I’m a jQuery novice. In particular, having an empty <span id="result_row"> seems incorrect. More importantly, it also imports the <td> tags into the <span> elements, which I’d like to avoid. All attempts to innerHTML failed (e.g. var date = $('td:eq(0)',this).innerHTML;
Thanks for any help,
Nick
EDIT: So now I can either do this three times
var date = $('td:eq(0)',this).text();
$('#date').text(date);
to avoid getting the <td> tags. Or I can do this
var data = $.find('td',this);
$('#date').html(data[0]);
$('#speaker').html(data[1]);
$('#title').html(data[2]);
which I think looks a lot clearer (and I assume the last three lines could be done in one). Sadly .text() doesn’t seem to work, so I’m stuck with <td>‘s in my output.
If you just want to get the data inside the
tds, use.html()or.text(). eg:In terms of doing it properly, loading html from a page (scraping) is rarely doing it properly. You should be getting the data from another source, such as json provided & formatted by the server etc. But if you must do it, your code looks fine to me 🙂