Javascript Set Style By Class Name

Build 1

Complete

Build 2

Incomplete

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

EDIT:

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
Share
Improve sầu this question
Follow
edited Jul 7 "15 at 22:17
kb_
asked Jul 7 "15 at 21:15
kb_kb_
29 1 1 silver badge 5 5 bronze badges
9
1
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
1
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
1

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>; el.style.backgroundMà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

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

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


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

Build 1

Complete

Build 2

Incomplete


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

Update

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

Complete

Build 2

Incomplete

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(element.style); element.style.display = "block"; console.log(element.style); .typeA

Build 1
Complete
Build 2
Incomplete

Share
Improve sầu this answer
Follow
edited Jul 8 "15 at 16:51
answered Jul 7 "15 at 22:34
StriplingWarriorStriplingWarrior
134k 23 23 gold badges 221 221 silver badges 277 277 bronze badges
6
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
Submit

Post as a guest


Name
Thư điện tử

Required, but never shown


Post as a guest


Name
E-Mail

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
Related
2722
How can I merge properties of two JavaScript objects dynamically?
2935
How can I change an element's class with JavaScript?
1677
Event binding on dynamically created elements?
1233
Get the name of an object's type
1321
How can I select an element by name with jQuery?
821
Is it possible lớn add dynamically named properties khổng lồ JavaScript object?
800
How lớn remove all CSS classes using jQuery/JavaScript?
902
How can I remove a style added with .css() function?
692
Chechồng if an element contains a class in JavaScript?
2918
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.


lang-js
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
*