• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Rob Spoor
  • Henry Wong
  • Liutauras Vilda
Saloon Keepers:
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
Bartenders:
  • Frits Walraven
  • Himai Minh
  • Jj Roberts

Selecting HTML sibling in DOM via tag instead of "previous"

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have a JS function that needs to extract the heading inside of a div box. The div box contains the button that fires this action. In a previous version of the code, the div just contained a heading, paragraph, and the button. So all I had to do was set the button's class to active and select the previous sibling.

However, the div is beginning to fill up and I'm having to list a lot of previous sibling calls, and it no longer grabs the correct element. Here is the code below:






Is there a way to grab a sibling via its tag?
 
Saloon Keeper
Posts: 12806
278
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why are you not using a MVVM framework? Manipulating the DOM with JavaScript manually is pretty old-school.

Anyway, you can do this pretty easily using Element.closest() and Element.querySelector():
 
Marshal
Posts: 67510
173
Mac Mac OS X IntelliJ IDE jQuery Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
At minimum, outside of adopting a whole new framework like React or Vue, jQuery is still the best way to vastly simplify JS.
 
Yeah. What he said. Totally. Wait. What? Sorry, I was looking at this tiny ad:
SKIP - a book about connecting industrious people with elderly land owners
https://coderanch.com/t/skip-book
reply
    Bookmark Topic Watch Topic
  • New Topic