Search code examples
jqueryhrefattr

Adding attribute 'href' of existing links to other links with Jquery


i want to create a mobile menu with Jquery but i'm failing with the reassignment of the href-attributes and text-attributes to the new links i created with Jquery. When i run console log on $(this).attr('href') and var $litext = $(this).text() everything seems fine. I just cant figure it out how to connect the new links with the two elements.

I made a JSFiddle: http://jsfiddle.net/14htwa2u/1/

var $navigation = '<div id="wrapper"><ul><li></li></ul></div>';
var $links = '<a class="dot"></a>';
$($navigation).append($links);

$('a').each(function(){


// Atrribut href
var $attribut = $(this).attr('href');

console.log($attribut);
// Text
var $litext = $(this).text();
console.log($litext);
// Verknüpfung
$($links).val($(this).attr('href', $attribut));

$($links).text($($litext).text());


console.log($links);
});

Thx 4 your help


Solution

  • You have to create each new link new.

    But at first, we append the list to the body and then we append each link with it's own li-element:

    $('<div id="wrapper"><ul></ul></div>').appendTo($("body"));
    
    $("a").each(function () {
        // get the href-attribute and the link-text
        var
        attribute = $(this).attr("href"),
        text = $(this).text();
    
        // log href and text
        console.log("attribute: ", attribute, " | text: ", text);
    
        // create new link with li in new navigation
        $('<li><a href="'+ attribute +'" class="dot">'+ text +'</a></li>').appendTo($("#wrapper ul"))
    })
    

    Here is your updated fiddle: http://jsfiddle.net/14htwa2u/4/