z-boss
z-boss

Reputation: 17618

How to add text to anchor with image?

I have an image link that I want to turn into image and text link.

Having this:

<a href="http://example.com/" class="link">  
  <img src="http://i.imgur.com/s3zp1u2.jpg" /></a>

I want to get this (notice 'Cat' text):

<a href="http://example.com/" class="link">  
  <img src="http://i.imgur.com/s3zp1u2.jpg" />Cat</a>

My code adds the text but removes the image:

$(function(){
    $('.link').text('Cat');
});

Upvotes: 0

Views: 226

Answers (4)

Andrew Kapunin
Andrew Kapunin

Reputation: 406

To what have already been suggested, I can only add a pure Javascript solution:

<a href="http://example.com/" class="link">  
  <img src="http://i.imgur.com/s3zp1u2.jpg" />
  <span id="cat-001-text">Cat</span>
</a>

<script type="text/javascript">
    document.getElementById("cat-001-text").innerHTML = "dog";
</script>

Upvotes: 0

NotJustin
NotJustin

Reputation: 529

One way:

$(function(){
    $('.link').append('Cat');
});

Upvotes: 1

C3roe
C3roe

Reputation: 96444

Use append instead of text.

$(function(){
    $('.link').append('Cat');
});

http://jsfiddle.net/0g8yuq0o/1/

Upvotes: 1

charlietfl
charlietfl

Reputation: 171700

Simplest would be to add an extra span

<a href="http://example.com/" class="link">  
  <img src="http://i.imgur.com/s3zp1u2.jpg" />
  <span></span>
</a>

js

$(function(){
    $('.link span').text('Cat');
});

AN alternative is to use append()

Upvotes: 2

Related Questions