JFFF
JFFF

Reputation: 989

How can you add an ID to dynamically generated href?

how can you add an ID to a link generated like this?

function addElement(list, pos) {
    var linkUrl = productList.products[pos].productLink;
    var linkItem = document.createElement('a');
    linkItem.setAttribute('href', linkUrl);

The previous code generates the following link

<a href="***/details.page?productId=3"><img src="***/topseller_main_en_1.png"></a>

Upvotes: 1

Views: 964

Answers (1)

James Johnson
James Johnson

Reputation: 46047

Try this:

function addElement(list, pos) { 
    var linkUrl = productList.products[pos].productLink; 
    var linkItem = document.createElement("a"); 
    if (linkItem){
        linkItem.id = "foo";
        linkItem.href = linkUrl;
    }
}

You can also do this in jQuery like this:

function addElement(list, pos) { 
    var linkUrl = productList.products[pos].productLink; 
    var linkItem = document.createElement("a"); 
    if (linkItem){
        linkItem.attr({ id : "foo", href : linkItem });
    }
}

Here's an even shorter way:

$("<a>").attr({ id : "foo", href : linkUrl });

Then just append it to an element in the document.

Upvotes: 5

Related Questions