user1525612
user1525612

Reputation: 1994

Javascript regex classname issue

Apologies for the vague title of this question!

I have the following JS, it looks for img tags with images of certain sources. It then replaces the img tag with a span so that I can replace the images/icons with iconfonts.

var paths = [       
    "folder%2Fadd",
    "folder%2Fclear",
    "folder%2Fdelete",
    "folder%2Fedit",
    "folder%2Fmove",
    "folder%2Fsort",
    ];


    var fullPaths = paths.map(function(x) { return "img[src*='" + x + "']"; } );
    var imgs = document.querySelectorAll(fullPaths);

        for (var i = 0; i < imgs.length; i++) {

            var span = document.createElement("span");
            span.addClass("iconfont");
            span.title = imgs[i].parentNode.title;
            imgs[i].parentNode.replaceChild(span, imgs[i]);


        }

Everything is working nicely so far, but there is one more issue that I cannot solve.

Apart from adding a class to the span of .iconfont, I also want to add two more classes to the span - 1) the original class of the replaced img element, and 2) the name of the image source as in my array, but without the 'folder/' bit in front.

So, at the moment I have:

<img class = "tinyicon" src="******/t/edit">

and my script creates this in the DOM:

<span class = "iconfont">

But I want my script to create the following:

<span class = "iconfont tinyicon edit">

That is what I am after :)

Thanks for having a look!

Upvotes: 3

Views: 88

Answers (3)

Arun P Johny
Arun P Johny

Reputation: 388316

        var span = document.createElement("span");
        var className = "iconfont " + imgs[i].className + ' ' + imgs[i].src.match(/([a-z])$/i, '')
        span.className  = className ;
        span.title = imgs[i].parentNode.title;
        imgs[i].parentNode.replaceChild(span, imgs[i]);

Upvotes: 1

jfriend00
jfriend00

Reputation: 707456

Change this:

 var span = document.createElement("span");
 span.addClass("iconfont");

to this:

 var span = document.createElement("span");
 span.className = "iconfont tinyicon edit";

Your addClass() wouldn't work anyway because span is a DOM node, not a jQuery object.

Upvotes: 1

adeneo
adeneo

Reputation: 318232

var paths = [       
    "folder%2Fadd",
    "folder%2Fclear",
    "folder%2Fdelete",
    "folder%2Fedit",
    "folder%2Fmove",
    "folder%2Fsort",
    ];


var fullPaths = paths.map(function(x) { return "img[src*='" + x + "']"; } );
var imgs = document.querySelectorAll(fullPaths);

for (var i = 0; i < imgs.length; i++) {
    var img    = imgs[i],
        iClass = img.className,
        iSrc   = img.src.split('/').pop(),
        span   = $('<span />', {'class': 'iconfont '+iClass+' '+iSrc,
                                title  : img.parentNode.title
                 });

    $(img).replaceWith(span);
}

Upvotes: 1

Related Questions