22

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?

3 Answers 3

34

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

Sign up to request clarification or add additional context in comments.

18 Comments

thanks @Sergio for your solution, can you please make a js-fiddle to showcase it. Sorry for my novice skills :P, but don't know how excatly to place this inside my html document.
@user2773294, just added demos to my answer.
thanks again @Sergio, I actually needed this within appropriate script tag with necessary jquery-lib path associated with this. Which I can simply take from here and place in my document head tag. I checked js-fiddle but it appears in same manner as it appears here, placing this inside my html document doesn't make it work.
@user2773294, you could do this with plain javascript, no jQuery. Check here jsfiddle.net/3sUvg/2
with your new-js fiddle I added the javascript code in my documents head section as given below.. <script type="text/javascript"> document.getElementById('my-link').innerHTML = '<a href="http://www.google.com">Google</a>'; </script> but it didn't work. Also I am using class-name instead id as selector for div (although I changed my class-name as id in html while tried your solution.).
|
3

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.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.