Search code examples
javascriptjqueryhrefattr

Using jQuery to change href after .load() call


I'm pretty new to web design but since some months I'm trying to learn some basic knowledge to work with html, css, JavaScript an so on. I've followed and tried to understand all the basic tutorials found on w3cschool and other introducting sites, with no particular problem with structure in html nor styling with css, but now I'm facing JavaScript and here's the question, but let me explain first what I'm trying to achieve.

On the site I'm triyng to conceive I've created a side panel which must contain some titles and short descriptions of articles taken from another site, with another domain. Due to my very poor experience and to the informations found on the web, I thought that jQuery could help me in this task, in particular with its load() method. So, after saving a copy in .txt format of the source page where the titles are, I wrote a very simple code in my document's head:

$(document).ready(function() {
    $("#myDiv1 p").load("copyOfSite.txt .list a:eq(0)");
    $("#myDiv2 p").load("copyOfSite.txt .list a:eq(1)");
    $("#myDiv3 p").load("copyOfSite.txt .list a:eq(2)");
});

This was working fine, except for the fact that the titles I am calling are relative links to articles with another domain, so they don't work in my site.

I've tried to specify a function in the second part of the load method but I couldn't find a way to prepend the domain of the other site to the href attribute I've loaded. I've only achieved to specify an url or to remove the loaded url with something like

$(document).ready(function() {
    $("#myDiv1 p").load("copyOfSite.txt .list a:eq(0)",function(data){
        $(this).find("[href]").attr('href','http://www.articlesdomain.com')}
    )};

or

$(document).ready(function() {
    $("#myDiv1 p").load("copyOfSite.txt .list a:eq(0)",function(data){
        $(this).find("[href]").removeAttr('href')}
    )};

but in both cases I cannot manage to call the href attribute of my loaded title and append to the articles domain. So I'm wondering if there's a way to achieve it or if my approach to the task is completely wrong.

Thanks in advance


Solution

  • You need to prepend the protocol and hostname to the already existing relative href's, right now you're replacing the entire href with the new url.
    Use a function to get each href, and just prepend the hostname to what's already there :

    $("#myDiv1 p").load("copyOfSite.txt .list a:eq(0)",function(data){
        $(this).find("[href]").attr('href', function(_,href) {
            return 'http://www.articlesdomain.com' + href;
        });
    )};
    

    note that the relative hrefs should start with /, otherwise you'll have to add that to the end of the prepended url as well