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.

2
  • You've tagged your question jquery, but your code doesn't use jQuery and your question doesn't mention it at all. Do you actually use it? Commented Dec 9, 2018 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. Commented Dec 9, 2018 at 13:27

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 - Just put an if inside the forEach callback: if (element.style.width == "512px") ...
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"});

1 Comment

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.
0
if (document.getElementById("gal").style.width = 513) { ...

Should become

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

You missed a =.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.