admin管理员组

文章数量:1332395

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.

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.

Share Improve this question edited Dec 9, 2018 at 15:21 Parsa Karami 7321 gold badge8 silver badges30 bronze badges asked Dec 9, 2018 at 13:23 DavidDavid 11 gold badge1 silver badge1 bronze badge 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? – T.J. Crowder 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 paring it (==, ===) with 513. – T.J. Crowder Commented Dec 9, 2018 at 13:27
Add a ment  | 

3 Answers 3

Reset to default 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.

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

Should bee

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

You missed a =.

本文标签: Javascript change css(“width”)Stack Overflow