• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Greenhorn
Posts: 22
  • 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: 15484
363
  • 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():
 
Sheriff
Posts: 67746
173
Mac Mac OS X IntelliJ IDE jQuery TypeScript Java iOS
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic