3

I have code

<div class="row1"> <em>My text</em> </div> 

How can I make a link like:

<div class="row1"> <em><a href="/mylink">My text</a></em> </div> 

I understand that the issue is a primitive but can not find the same simple solution.

6 Answers 6

5

You can use contents() with wrapAll():

$(".row1 em").contents().wrapAll("<a href='/mylink'></a>"); 
Sign up to request clarification or add additional context in comments.

3 Comments

@Eric, sorry, I did not see your answer when I posted mine :)
It's ok. You remembered to post the docs links, which in many ways is better.
4
$('.row1 em').html(function(i, contents) { return '<a href="/mylink">' + contents + '</a>'; }); 

or

 $('.row1 em').contents().wrapAll('<a href="/mylink" />'); 

Comments

0

you can try this-

$(".row1 em").contents().wrapAll("<a href='/mylink'></a>") 

2 Comments

Duplicate of mine and @Frédéric Hamidi's answer
then what...every one here is having right to write there suggestion if matches with other answer's what's problem in that...
-1
$('.row1 em').html().wrap('<a href="/mylink">'); 

2 Comments

Wrong! .html() returns a string!
Yep - you're right this answer is totally wrong. I'm not going to edit it
-1

If your aim is to hyperlink the text, and you can afford alternate solutions, following achieves the same:

HTML:

<div class="row1"> <em>My text</em> </div> 

CSS:

.row1 { cursor:pointer; } 

JS:

$('.em').click(function() { location.href = '/mylink'; }); 

2 Comments

No! Do not create links in JavaScript, they are horrible on usability. What if I don't have JS enabled? What if I want to open the link into another tab? What if I want to see where the link leads before clicking?
Agreed on other counts, but not on JS being disabled, since the question itself is tagged with javascript/jquery, and various other solutions too use jquery.
-1

Example:

$('.row1 em').wrap('<a href="/mylink" />'); 

Update: Since this will wrap the <a> tags around <em> instead its contents, the correct way is to use $('.row1 em').contents().wrap('<a href="/mylink" />'); as Frederic stated

4 Comments

Wrong! That'll put the <a> around the <em>.
I don't see how changing the order in which those tags appear justifies a downvote. em inside a is perfectly valid
Possibly because that's not what the question asked for?
Yes, it's not quite as I described in the job, but none the less. this solution works and I am quite fit. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.