bwa35 bwa35 - 6 months ago 12
Javascript Question

How to insert a small image Icon next to a repeated link using jquery

I am a beginner with Jquery and I am looking to add a small image of a person next to their name which is an href link above a blog post. The link is of the bloggers name and I want to add their image next to it however I have no idea how to do this. I know how to insert an image however I am not sure how to insert the Image repeatedly whenever the blogger creates a new post? Any help would be much appreciated

eg. (image here) Bill Smith | 22nd November 2014

so whenever that person creates a post their image appears before it
This is what I have so far however it doesn't do anything. The author is the class the authors name is in.

$('<img src="https://www.people.com/bill.jpg" />').insertBefore('author');


html:

<article class="blogpost">
<p class="author">
<a href="https://people.com/billsmith">Bill Smith</a>
</p>
</article>

Answer

You need to loop over each instance of the author paragraph:

$('p.author').each(function() {
    $('<img src="http://placehold.it/30x30" />').insertBefore($(this));
});

Demo

The problem will be associating a specific image with each author. To do that you'll need to parse the text string in that paragraph and process it according to your image naming convention. This all becomes very cumbersome and fragile, and gibberish's answer offers a better solution.