user2773294
user2773294

Reputation: 223

how to add text link inside a div using jquery?

I want to place some text as link inside a div.

For example, I want to place text 'Google' with hyperlink <a href="http://www.google.com" inside a div having class-id as "my-link".

How can this be done using jquery or javascript?

Upvotes: 22

Views: 58983

Answers (3)

Sergio
Sergio

Reputation: 28837

Class and ID is not the same.

If ID try this:

$('#my-link').html('<a href="http://www.google.com">Google</a>');

Demo with ID

If Class try this:

$('.my-link').html('<a href="http://www.google.com">Google</a>');
   ^

Demo with class

Upvotes: 34

Subin
Subin

Reputation: 3563

You can do this :

$('.my-link').html('<a href="http://www.google.com">Google</a>');

but it would add hyperlink to all .my-link divs, so it's better to add an ID to div and use the ID on jQuery code.

Upvotes: 3

Arun P Johny
Arun P Johny

Reputation: 388316

If my-link is the class of the target div then

$('.my-link').html(function(idx, html){
    return html.replace(/Google/g, '<a href="http://www.google.com">Google</a>')
})

Demo: Fiddle

Upvotes: 2

Related Questions