Skip to content
Advertisement

Selecting previous element in DOM

I’m having a hard time with some JS DOM traversal. I’m stuck with html that’s something like this:

JavaScript

This is all hidden by default. I’m trying to use a text field so that if it matches an h4 person-name, it displays the some-content container, as well as the preceding h2. I can make it work for the some-content bit, but I’m having trouble targeting the h2 that’s above it. I’ve tried various combinations of jQuery parent(), siblings(), and prev(). I do not have the ability to add additional class names.

Edit: here is the script I have for the text field event:

JavaScript

Edit 2:

I apologize, my code example was oversimplified. Some very good answers by the way. If for example there was a search done for Emily Jones in this bit, would there need to be something extra done?

JavaScript

Advertisement

Answer

If the header/content is not nested withing a wrapping div, you will need to step over every two child nodes and toggle class.

JavaScript
JavaScript
JavaScript

Alternatively, you can start with the names and work your way back to the corresponding h2.

JavaScript

JavaScript
JavaScript
JavaScript

Edit

Here is an altered version of the first example. If you have multiple names within .some-content you will have to find all the names that match and keep the parent, if at least one child matches.

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement