質問でリンクしたページをざっと見てみると、ユーザー名を囲むマークアップは次のように見えます(おそらく、ユーザー名を例として使用します)。
<a href="http://www.reddit.com/user/DiscontentDisciple" class="author id-t2_4allq" >DiscontentDisciple</a>
その場合、jQueryライブラリが利用可能である場合(ここでも、あなたの質問から)、1つのアプローチは単純に次を使用することです。
var authors = [];
$('a.author').html(
function(i, h) {
var authorName = $(this).text();
if ($.inArray(authorName, authors) == -1) {
authors.push(authorName); // an array of author-names
}
return '<img src="path/to/' + encodeURIComponent(authorName) + '-image.png" / >' + h;
});
console.log(authors);
JSFiddleの概念実証。
a
または、同様に、ユーザー名が要素のhref
属性のURLの最後の部分であると予想されるという事実を使用します。
var authors = [];
$('a.author').html(
function(i, h) {
var authorName = this.href.split('/').pop();
if ($.inArray(authorName, authors) == -1) {
authors.push(authorName);
}
return '<img src="http://www.example.com/path/to/' + authorName+ '-image.png" />' + h;
});
console.log(authors);
JSFiddleの概念実証。
これらのアプローチは両方とも、要素img
内に配置されます。要素の前にそれa
が必要な場合は、単に次を使用します。a
// creates an 'authors' variable, and sets it to be an array.
var authors = [];
$('a.author').each( // iterates through each element returned by the selector
function() {
var that = this, // caches the this variable, rather than re-examining the DOM.
// takes the href of the current element, splits it on the '/' characters,
// and returns the *last* of the elements from the array formed by split()
authorName = that.href.split('/').pop();
// looks to see if the current authorName is in the authors array, if it *isn't*
// the $.inArray returns -1 (like indexOf())
if ($.inArray(authorName, authors) == -1) {
// if authorName not already in the array it's added to the array using
// push()
authors.push(authorName);
}
// creates an image element, concatenates the authorName variable into the
// src attribute-value
$('<img src="http://www.example.com/path/to/' + authorName+ '-image.png" />')
// inserts the image before the current (though converted to a jQuery
// object in order to use insertBefore()
.insertBefore($(that));
});
console.log(authors);
JSFiddleの概念実証。
参照: