navigating up and down html elements using css selectors

Within my code, I have this odd repetitive HTML structure (with no classes) and I'm looking to extract all links along with the accompanying text below each link.

While it's simple enough to grab all the links using a basic CSS query selector like a, I also need to retrieve the text located within a sibling element of the ancestor of each link. This requires traversing up through the levels of divs before moving back down again.

Does anyone have any suggestions on how to ascend and then descend using a CSS selector?

...
...
...

<div>                                   <----first level of div
    <div>                               <----second level of div
        <span>
            <span>
                <div>                   <----third level of div
                    <a href="">         <----element that I can easily capture
                </div>
            </span>
        </span>
    </div>
    <div></div>
    <div>
        <span>
            <span>
                text to capture        <----text I am trying to obtain
            </span>
        </span>
    </div>

<div>
...
...
...

Answer №1

When navigating the DOM, remember to use .parent() to move up a level, .children() to go down, and .next() to access the next sibling element. By combining these methods effectively, you can traverse from an a tag to the text span directly below it.

let result = $();
$("a").each(function() {
    let first_level = $(this).parent().parent().parent().parent();
    let sibling = first_level().next().next();
    let text_element = sibling.children().children()
    result = result.add(this).add(text_element);
})

Answer №2

As of now, there is no direct CSS parent selector available.

If the structure of your document follows the example you provided, navigating through the DOM is quite simple.

Array.from(document.querySelectorAll('a')).forEach(a => {
  let node = a;
  for (let i = 0; i < 5; i++) node = node.parentNode;
  console.log(a.innerText + ' : ' + node.children[2].children[0].children[0].innerText);
});
<div>
    <div>
        <span>
            <span>
                <div>
                    <a href="">Link 1</a>
                </div>
            </span>
        </span>
    </div>
    <div></div>
    <div>
        <span>
            <span>
                text to capture 1
            </span>
        </span>
    </div>
<div>
<div>
    <div>
        <span>
            <span>
                <div>
                    <a href="">Link 2</a>
                </div>
            </span>
        </span>
    </div>
    <div></div>
    <div>
        <span>
            <span>
                text to capture 2
            </span>
        </span>
    </div>
<div>
<div>
    <div>
        <span>
            <span>
                <div>
                    <a href="">Link 3</a>
                </div>
            </span>
        </span>
    </div>
    <div></div>
    <div>
        <span>
            <span>
                text to capture 3
            </span>
        </span>
    </div>
<div>
<div>
    <div>
        <span>
            <span>
                <div>
                    <a href="">Link 4</a>
                </div>
            </span>
        </span>
    </div>
    <div></div>
    <div>
        <span>
            <span>
                text to capture 4
            </span>
        </span>
    </div>
<div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unexpected behavior in AJAX call

I'm currently working on implementing an AJAX call to display a partial view once a radio button is selected. Despite following the recommendations found on Stack Overflow comments, I am encountering difficulties. Upon selecting the radio button, ther ...

What is the reason for the disappearance of unordered list bullets when using padding: 0?

Updating an older website that contains numerous unordered lists has presented a challenge. When the padding is set to 0, the display markers on the unordered list disappear. The root cause of this issue was traced back to the CSS setting *{padding: 0; ma ...

Challenges with Aligning Panels in Column 6

My initial encounter with bootstrap was interesting. I attempted to have two panels placed side by side using the col-lg-6 class. The left panel was meant to be a link to an article, along with an image, while the right panel would serve as a signup/login ...

Error encountered on Facebook Like button: The large button is failing to show the total number of likes received

Despite functioning flawlessly for months, the large Facebook Like button has suddenly stopped showing the number of "Likes". Strangely, the compact version is still working fine, but the larger button is concealing the count. I am using a Mac and have obs ...

Omit any items from an array that do not have any child elements

Upon receiving data from the server in the format of a flat tree, I proceed to transfer this data to the JsTree library for tree building. Before sending the data to JsTree, I filter out any empty elements of type "folder" that do not have children. Below ...

Simple 3-column grid design in HTML and CSS

My task is to design a 3-grid layout that resembles the following structure: ------------------------------------- | Image | The name of logo | > | ------------------------------------- I attempted this using the code below: <div class=" ...

reveal concealed section and seamlessly glide to specified location inside the secret compartment

I have implemented a feature on my website where hidden divs are revealed one at a time, with the screen scrolling to display each specific div. While this code functions well, I am now looking to enhance it by opening the hidden div and smoothly scrolling ...

Is there a way to ensure that the 'pointermove' event continues to trigger even after the dialog element has been closed?

I am working on a project that involves allowing users to drag elements from a modal dialog and drop them onto the page. I have implemented a feature where dialog.close() is called once the user starts dragging. This functionality works perfectly on deskto ...

Troubleshooting jQuery masonry problem related to initial display and height settings

Within a div, there is a masonry container with the inline style property display:none. With several divs on the page, clicking their respective buttons during load causes them to switch like a slideshow. This disrupts masonry's ability to calculate t ...

Why is the radio button getting bound to the error instead of the label?

I'm currently working on validating radio buttons in a GSP file using the jQuery validation plugin. The issue I'm facing is that the error message is being bound to the first radio button and appearing at the bottom of it. Instead of displaying ...

Encountering an issue with retrieving the nth element using Python Selenium

<div class="booking-classes"> <h3 style="text-align: center;"> <p><a href="https://foreupsoftware.com/index.php/booking/20290#/teetimes" style="background-position:0px 0px;"><b> ...

Tips for adjusting the close date based on the selected date in a dropdown datepicker

Here is a sample code snippet: <input id="date1" name="start_date" id="dpd1"/> <select class="form_line_only form-control" name="ho_night"> <option selected> 0 </option> <option ...

Trigger an AJAX request in jQuery to display an error message upon encountering a PHP error during form validation

There have been instances where I utilized PHP validation to display an error message if a certain field was left empty, as shown below: if(empty($_POST['formfield'])) { echo "Error"; die(); } else { ... } Additionally, I used jQuery valida ...

Enhance your web design with the mesmerizing jQuery UI drop effect combined

I'm attempting to create an animated toggle effect on a box using jQuery UI's drop feature. However, I've encountered some trouble due to the box having box-sizing: border-box applied which is causing issues with the animation. During the a ...

Return to the beginning using Jquery Mobile

Currently, I am working on developing a mobile web app using jQuery Mobile. I am now looking to implement a back-to-top action. Typically, this can be done with the following code snippet: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ...

Adding a delay between calls to the addClass() function in jQuery

Having trouble setting my delay as described in this post: jQuery: Can I call delay() between addClass() and such? Unfortunately, it's not working for me. JSFiddle $( "#nav2" ).click(function() { var notshown = $("#dropdown1", "#dropdown2"); ...

Turning a JavaScript function into jQuery

Is there a way to convert this JavaScript selected code into jQuery? I need to target a button class instead of an ID, and I've heard that using jQuery is the simplest way to achieve this. var playButton1 = $('.playButton1'); playButton1.o ...

Ways to modify the .MuiSelect-nativeInput element within Material-UI

const styles = makeStyles((theme) => ({ root: { margin: "0px 20px" }, textStyle: { fontFamily: "Comfortaa", }, container: {}, textField: { fontFamily: "Comfortaa", }, dropDownFormSize: { width: &qu ...

Unable to vertically scroll on a position fixed element

I recently created a unique VueJS component that enables vertical scrolling. Within this component, there are two elements each with a height of 100vh. At the bottom of the component is a fixed position div. Interestingly, when I try to scroll down using m ...

Determine if a radio button is in an enabled or disabled state

<div id="statusOptions"> <label><input type="radio" name="status" value="T" checked> Temporary Waiver</label> <label><input type="radio" name="status" value="P"> Never Expires</label> <label><i ...