Apply CSS using element class (JS)

Asked

Viewed 125 times

2

[STUDY ONLY]

When clicking a button, I need to make the function apply a width to the elements with the class "border_title_result".

function spanSize(){
                var div = document.getElementById('title_result');
                var size = 700 - div.offsetWidth;
                var f = size + "px";
                console.log(f);

                document.getElementsByClassName('border_title_result').style.width = f;
            }

The width is defined according to the size of a div - 700px;

I’ve tested it using 'getElementById' for only one element, but I don’t know how I can apply this same css to several elements.

The elements are dynamic, they are written using PHP, so I can’t just make a variable for each element id.

This is purely for study, I just want to learn how to plicate js using class.

  • 1

    John, take a look at the duplicate, the principle is the same. Have to use for to traverse the elements by the class.

1 answer

1


To do this you can count on jQuery

https://jquery.com/

With it you could just do

$('.border_title_result').each(function (){
     this.css('width', f)
})

Now if you really want to use pure JS try:

function spanSize() {
    var div = document.getElementById('title_result');
    var size = 700 - div.offsetWidth;
    var f = size + "px";
    console.log(f);

    var borderTitleResults = document.querySelectorAll(".border_title_result")

    for (i = 0; i < borderTitleResults.length; i++) {
        borderTitleResults[i].style.width = f;
    }

    //ES6
    borderTitleResults.map(i => i.style.width = f)
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.