Javascript Set Style By Class Name

Build 1


Build 2


//about 6 or 7 more builds...

I need to lớn access the style of build# lớn change the display...all are originally hidden but I hava java code that creates a string/s (ex. "build2" and "build3"). I have sầu that string saved as "tempKey" in my JAVA code.

Bạn đang xem: Javascript set style by class name

Then in a javascript script:

var tempKey = "<%=tempKey%>"; document.getElementsByClassName(tempKey).style.display = "block !important";

I have sầu also tried adding a class "active" and had that class have the same style (bloông xã !important), plus a number of different ways to lớn solve sầu this. It seems I just can"t access the element right using the java string in a javascript function.


I am accessing the right element, but it won"t let me overwrite the display style from none to lớn bloông xã. For some reason !important is not working...

javascript dom classname
Improve sầu this question
edited Jul 7 "15 at 22:17
asked Jul 7 "15 at 21:15
29 1 1 silver badge 5 5 bronze badges
When you're saying Java, vì chưng you mean JavaScript? – Surreal Dreams Jul 7 "15 at 21:16
No. It is in Java. <%String tempKey = ..... %>. – kb_ Jul 7 "15 at 21:24
Are you using some kind of templating framework? – habsq Jul 7 "15 at 21:25
Have sầu you looked at your resulting HTML DOM in the browser and checked if the style is applied? We would know if it is a CSS problem or a JS-Problem. – D.R. Jul 7 "15 at 21:29
Ok. So in my code, say in the example above the class typeA has a style display of "none". I am trying lớn phối "build2"'s style display khổng lồ "block" lớn overwrite it. – kb_ Jul 7 "15 at 21:40
 |  Show 4 more comments

2 Answers 2

Active sầu Oldest Votes

Rethành viên that the selector returns an array so you need to supply the index <0>.

var i = 3; var tempKey = "build" + i; var el = document.getElementsByClassName(tempKey)<0>;àu sắc = "#FFCC00"; ul.type-list ul.type-list li.typeA ul.type-các mục li span.b

  • Build 1 Complete
  • Build 2 Incomplete
  • Build 3 build3
  • Build 4 build4

Improve this answer
answered Jul 7 "15 at 22:40
2,431 1 1 gold badge 9 9 silver badges 11 11 bronze badges
Add a phản hồi  | 

getElementsByClassName() produces an array of items. You need to lớn index inkhổng lồ it:

var element = document.getElementsByClassName("build1")<0>; console.log(; = "block"; console.log(; .typeA

Build 1


Build 2


And there"s no need for !important because an individual element"s style supercedes all the other styles that it would have sầu inherited.

Xem thêm: Bệnh Nấm Candida Ở Phụ Nữ - Nhiễm Nấm Candida: Nguyên Nhân


The real problem here is that HTML rules don"t allow

elements khổng lồ contain

elements, so the browser is automatically closing the

tags for you, producing this DOM:

Build 1


Build 2


This makes it so that your inner divs aren"t actually children of your p tags. Try using another element, lượt thích divs, for your outer containers.

var element = document.getElementsByClassName("build1")<0>; console.log(; = "block"; console.log(; .typeA

Build 1
Build 2

Improve sầu this answer
edited Jul 8 "15 at 16:51
answered Jul 7 "15 at 22:34
134k 23 23 gold badges 221 221 silver badges 277 277 bronze badges
This still isn't working. Looking at the resulting HTML DOM in the browser, it picks up that I tried lớn change the display but is crossed out/inactive và shows that typeA wants "none". – kb_ Jul 7 "15 at 22:42
To convert a java string khổng lồ a javascript variable is this correct? var tempKey = "<%=tempKey%>" – kb_ Jul 7 "15 at 22:43
kb_: See my update. And no, the code that you just posted to lớn convert a java string khổng lồ a javascript variable would break if your string happens to lớn have a double-quote character (") in it. I'd suggest you use a JSON converter library of some kind. var tempKey = <%=JsonWriter.objectToJson(tempKey)%>; – StriplingWarrior Jul 8 "15 at 16:50
I will try changing the

. For your other suggestion: my original tempKey is a value that I pulled from an external JSON.. why would I convert it bachồng lớn a JSON? – kb_ Jul 8 "15 at 21:40
kb_: Presumably tempKey is a Java String right? The correct JSON representation of "say "hello"" when JSON-serialized is "say "hello"", which is exactly what you want to have sầu show up in your rendered output. – StriplingWarrior Jul 8 "15 at 22:06
 |  Show 1 more comments

Your Answer

Thanks for contributing an answer to Stack Overflow!

Please be sure to answer the question. Provide details and share your research!

But avoid

Asking for help, clarification, or responding lớn other answers.Making statements based on opinion; baông chồng them up with references or personal experience.

To learn more, see our tips on writing great answers.

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Facebook
Sign up using Thư điện tử và Password

Post as a guest

Thư điện tử

Required, but never shown

Post as a guest


Required, but never shown

Post Your Answer Discard

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged javascript dom classname or ask your own question.

The Overflow Blog
Podcast 317: Chatting with Google’s DeepMind about the future of AI
Level Up: Mastering statistics with Python – part 4
Featured on Meta
Visual thiết kế changes to the Review queues
Survey questions for outdated answers
Introducing Outdated Answers project
How can I merge properties of two JavaScript objects dynamically?
How can I change an element's class with JavaScript?
Event binding on dynamically created elements?
Get the name of an object's type
How can I select an element by name with jQuery?
Is it possible lớn add dynamically named properties khổng lồ JavaScript object?
How lớn remove all CSS classes using jQuery/JavaScript?
How can I remove a style added with .css() function?
Chechồng if an element contains a class in JavaScript?
Is it possible to apply CSS khổng lồ half of a character?
Hot Network Questions
Should I quit a PhD with little supervision at a prestigious university & start a new PhD?
Scan through (partial) tuples
How can I run newer Unity games on OS X 10.9 Mavericks?
Should I address a "Charge de Recherche" or "Directeur de recherche" in France as "Prof."?
Aligning equations with alignat & vertical dots
"My father declared he should invent a slip button"
In Guardians of the Galaxy Volume 2, How can two people (Rocket và Quill) both pilot the Milano or Benatar spacecraft?
Saturn V's blueprints
Philosophy on stored procedures that perkhung updates: is a 'granular' update approach sufficient?
When you are winning, is it ethical to not go for a checkmate right away?
C++ Fast Fourier transform
How should I make a realistic cucumber?
Primes and Twin Primes
How vị I help a player terrified of their character dying in combat?
Backyard wildlife zoom question factoring distance
What is the opposite of 'owe'?
Triông chồng khổng lồ rethành viên which instance I am working with
Classical Guitar: Can someone reference this piece of music allegedly by Carulli
How does anyone ever die with a Cleric
Is Scrooge McDuông chồng immortal?
Notes in a Chord
Optocoupler with the same power supply
Are nuclear armed missiles effective weapons for spaceborne combat?
Word "believe" in scientific context more hot questions
Question feed
Subscribe lớn RSS
Question feed

To subscribe to this RSS feed, copy và paste this URL inlớn your RSS reader.

Staông xã Overflow Questions Jobs Developer Jobs Directory Salary Calculator Help điện thoại
Products Teams Talent Advertising Enterprise
Company About Press Work Here Legal Privacy Policy Terms of Service Contact Us
Staông chồng Exchange Network Technology Life / Arts Culture / Recreation Science Other
Staông xã Overflow Server Fault Super User Web Applications Ask Ubuntu Webmasters Game Development
TeX - LaTeX Software Engineering Unix & Linux Ask Different (Apple) WordPress Development Geographic Information Systems Electrical Engineering
Android Enthusiasts Information Security Database Administrators Drupal Answers SharePoint User Experience Mathematica
Salesforce ExpressionEngine® Answers Stack Overflow em Português Blender Network Engineering Cryptography Code đánh giá
Magento Software Recommendations Signal Processing Emacs Raspberry Pi Staông chồng Overflow на русском Code Golf
Staông xã Overflow en español Ethereum Data Science Arduino Bitcoin Software Quality Assurance & Testing Sound Design
Windows Phone more (28)
Photography Science Fiction & Fantasy Graphic Design Movies & TV Music: Practice & Theory Worldbuilding Video Production
Seasoned Advice (cooking) trang chủ Improvement Personal Finance & Money Academia Law Physical Fitness Gardening & Landscaping
Parenting more (10)
English Language & Usage Skeptics Mi Yodeya (Judaism) Travel Christianity English Language Learners Japanese Language
Chinese Language French Language German Language Biblical Hermeneutics History Spanish Language Islam
Русский язык Russian Language Arqade (gaming) Bicycles Role-playing Games Anime & Manga Puzzling
Motor Vehicle Maintenance & Repair Board & Card Games Bricks Homebrewing Martial Arts The Great Outdoors Poker
Chess Sports more (16)
MathOverflow Mathematics Cross Validated (stats) Theoretical Computer Science Physics Chemistry Biology
Computer Science Philosophy Linguistics Psychology & Neuroscience Computational Science more (10)
Meta Stack Exchange Staông xã Apps API Data
Blog Facebook Twitter LinkedIn Instagram

site kiến thiết / logo © 2021 Staông xã Exchange Inc; user contributions licensed under cc by-sa. rev 2021.3.2.38685

Stachồng Overflow works best with JavaScript enabled