Pregunta

I have a div which contains many divs. All of these subdivs have a number of classes that match a certain naming pattern. I have many classes named like "tile1Full","tile1Thumb","BG1Full","BG1Thumb". So my html might look like this:

<div id=parent>
    <div>
        <div class='tile1Full BG2Full border1'>
    </div>
    <div>
        <div class='tile3ContainerFull border1'>
            <div class=tile2x2Full border3></div>
        </div>
    </div>

I would like to replace all classes that have "Full" in the name with their "Thumb" counterpart, so the result would be this:

<div id=parent>
    <div>
        <div class='tile1Thumb BG2Thumb border1'>
    </div>
    <div>
        <div class='tile3ContainerThumb border1'>
        <div class=tile2x2Thumb border3></div>
    </div>
</div>

Here is what I came up with:

contents.find('div').each(function (i) {
    if ($(this).attr('class')!==undefined)
    {
        $(this).attr('class',$(this).attr('class').replace(/Full/g,'Thumb'));
    }
});

The problem is, according to Firefox "Inspect Element", when I look at the class attribute, the new class names are there. However, when I look at the CSS inspector, those classes are not actually being applied. It no longer applies the "Full" classes, as expected, but it does not apply the "Thumb" classes either.

One of the things the class does is set the width and height of the div. The divs themselves contain no content; just background images, so since the new classes are not being applied, they all have widths and heights of 0 and in effect disappear.

Why would the attribute inspector report that they have the desired class, but then the CSS inspector shows that those classes are not being applied?

Thanks

¿Fue útil?

Solución

you can do it like this

$(document.body).find('div').each(function (i) {
    var c = $(this).attr('class');
    if(c !== undefined){
        c = c.replace(/Full/g,'Thumb')
        $(this).removeClass().addClass(c);
    }
});

see here http://jsfiddle.net/95tQA/1/

Otros consejos

I think you can get it working using heavy use of this part of .attr(attr, fn). I haven't had a chance to test it, set up a fiddle and I'll get it working but try:

contents.find('div').attr("class", function (idx, cls) {
    if(/Full/.test(cls) {
        return cls.replace(/Full/g, 'Thumb');
    }
});

Quick test:

var $a = $("<div>", {"class": "test bgFull yo test2"});
$a.attr("class", function (idx, cls) {
    return cls.replace(/Full/g, 'Thumb');
});
$a.attr("class"); // 'test bgThumb yo test2'

This is propaply some thing of internal propagation method that goes wrong here... Did you try using the jQuery function addClass() and removeClass()? This would propaply look cleaner to.

Cheers,
Florian

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top