David
David

Reputation: 1

Javascript change css(“width”)?

if(document.getElementById("gal").style.width = 513) {
    document.getElementById("gal").style.width = "25%";
    document.getElementById("gal").style.height = "auto";
}

I'm trying to change default width for certain image width added on Gallery.

This code perfectly work, the problem is that getelementbyid changed just the first element of the gallery.

How can i do the same, using getelementsbyclassname? Or are there any other way to change all of the id's style?

Thanks in advance.

Upvotes: 0

Views: 20727

Answers (3)

ImmanuelNL
ImmanuelNL

Reputation: 31

if (document.getElementById("gal").style.width = 513) { ...

Should become

if (document.getElementById("gal").style.width == 513) {

You missed a =.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1073998

If you actually use jQuery (you've tagged your question with it, but haven't used it anywhere), changing the width and height of all elements matching a selector is really easy using jQuery's css function:

$("your-selector-here").css({
    width: "25%",
    height: "auto"
});

If you don't use jQuery, you use querySelectorAll and a loop, for instance:

document.querySelectorAll("your-selector-here").forEach(function(element) {
    element.style.width = "25%";
    element.style.height = "auto";
});

The NodeList returned by querySelectorAll only got the forEach method fairly recently. See this answer for how to ensure that it exists on the browser you're using.

Upvotes: 2

Ayaz Ali Shah
Ayaz Ali Shah

Reputation: 3531

As you added jquery tag which means you are jquery. So if you are using jquery then why not to use jquery built-in css() function.

$(".your-class").css("width": "25%");
$(".your-class").css("height": "auto");

OR

$(".your-class").css({"width": "25%", "height": "auto"});

Upvotes: 1

Related Questions