0
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.

Parsa Karami
  • 702
  • 1
  • 8
  • 30
David
  • 1
  • 1
  • 1
  • 1
  • You've tagged your question [tag:jquery], but your code doesn't use jQuery and your question doesn't mention it at all. Do you actually use it? – T.J. Crowder Dec 09 '18 at 13:26
  • 2
    *"This code perfectly work..."* Not as shown it doesn't. The `if` condition is always true, because you're **assigning** (`=`) 513 to `width` and then testing the result, not comparing it (`==`, `===`) with 513. – T.J. Crowder Dec 09 '18 at 13:27

3 Answers3

1

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"});
Ayaz Ali Shah
  • 3,453
  • 9
  • 36
  • 68
  • Thanks for your answer. My gallery has a css inilne. I have to modify the images, when they have 512px, they must become 25%, when they have 1024, they must become 50%, the "tile" class and the "gal" id are repeated in all the photos. – David Dec 09 '18 at 13:50
1

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thanks. Your code is working but for all my gallery divs (all divs have an inline css). I need that div width 512px width, will become 25% (as the code you sent) but div width 1024px, will become 50% – David Dec 09 '18 at 14:08
  • @David - Just put an `if` inside the `forEach` callback: `if (element.style.width == "512px")` ... – T.J. Crowder Dec 10 '18 at 08:01
0
if (document.getElementById("gal").style.width = 513) { ...

Should become

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

You missed a =.

ImmanuelNL
  • 31
  • 1
  • 5