Faithful Faithful - 2 months ago 8
HTML Question

jquery var = text + number

I have a bullet list

<ul>
with custom bullet icons. I need some kind of javascript that will go through my list and check if icon- has a number after it, if it does than add an
<img>
tag and add the icon- + number as a class as each icon- + number will be a different icon.

See my code below.

Thanks in advance for your help

HTML

<ul class="someclass">
<li>
<div class="divClass">
[icon-1]
</div>
Some Text
</li>

<li>
<div class="divClass">
[icon-2]
</div>
Some Other Text
</li>
</ul>


Javascript attempt

$(".someclass .divClass").each(function() {
var icon = [icon + number]

$(".divClass:contains('icon')").text().replace('<img class="icon" src="img/path/pic.png" alt="Bullet List Icon" />');
});

Answer

Try this

var i = 1; 
    $(".someclass .divClass").each(function() {  

        var icon = "[icon-" + i++ +"]"; 

    $(".divClass:contains('"+icon+"')").html('<img class="icon" src="img/path/pic.png" alt="Bullet List Icon" />');
});

UPDATE: Keep the li text :

var i = 1; 
    $(".someclass li").each(function() {  

        var icon = "[icon-" + i++ +"]"; 
        var liText = $(this).text(); // Get all text of li element
        liText = liText.replace(icon, "");// Remove the [icon-i] string from the text. 
    $(".someclass li:contains('"+icon+"')").html('<img class="icon" src="img/path/pic.png" alt="Bullet List Icon" />'+ liText);
});
Comments