How to Set a new class is not applied on Bootstrap and jQuery?

the point of the function is to make the column in a row bigger or smaller and do it by changing the class name by javascript.

The row and column is defined by Bootstrap's usually:

<div class="row">
    <div id="myColumn" class="col-lg-5">
        <!-- Some Content -->
    </div>
</div>

Now if I set the classes of the element #myColumn there is no change neither visible or in the HTML.

I've tried the following:

1) $element.attr("class", classes);

2) $element.prop("class", classes);

3) document.getElementById("myColumn").className = classes;

4) $element.attr("class", null); $element.attr("class", classes);

5) Very awkward and ugly attempts to work-arround, but none was successful

There is no change applied at all, however if I run command from the browser's console it runs as expected, but not from the script. The script is every time fresh, not cached.

Fun fact: When I do the following: $element.attr("class", null); the classes will disappear, but when I enter the class names, it's like the .attr("class", null); takes no effect and nothing happens.

Here are the snippets of the JavaScript code:

var biggerCol = ($element) => {
    var newClasses = [];
    var classes = $element.attr("class").split(' ');

    for(var index in classes) {
        if(classes[index].startsWith("col-")) {
            var splitted = classes[index].split('-');
            newClasses.push("col-" + splitted[1] + "-" + (parseInt(splitted[2]) + 1));
        }
        else {
            newClasses.push(classes[index]);
        }
    }

    console.log(newClasses.join(' '));
    $element.attr("class", newClasses.join(' '));
};

var smallerCol = ($element) => {
    var newClasses = [];
    var classes = $element.attr("class").split(' ');

    for(var index in classes) {
        if(classes[index].startsWith("col-")) {
            var splitted = classes[index].split('-');
            newClasses.push("col-" + splitted[1] + "-" + (parseInt(splitted[2]) - 1));
        }
        else {
            newClasses.push(classes[index]);
        }
    }


    $element.attr("class", newClasses.join(' '));
}

As you can see the console.log the following is returned:

col-lg-5 col-md-5 col-sm-7 col-xs-13 column1 to-left-column als-vertical which is as expected and correct to what I want.

My guess is that it has to do something with Bootstrap and jQuery combined.

1 answer

  • answered 2019-03-14 10:42 Marin Mouscadet

    The problem is that the order by which the class are rank. One way to do it, is to put the !important tag in your custom CSS. However, you could try to add your custom class in the first position.

    Tell me if you need more help!