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

Pause the YouTube video when the modal is closed, following an AJAX load

I'm facing an issue with a small script that is supposed to stop YouTube videos from playing once their modals are closed. The problem arises when the HTML content is loaded through AJAX. Here is the script: $('#panelModal-1').on(&apos ...

Unable to send a value to a CodeIgniter controller using AJAX

I am attempting to create an update function using ajax with two parameters that need to be passed to my CI controller. However, I encountered an error and suspected that the parameters were not being correctly passed to the controller. Below is the ajax ...

Generate a hard copy of the data table row without needing to view it beforehand

Here are some records from a table: +--------+---------+-------+----------+--------+ | Name | Address | Phone + Email | Action | +--------+---------+-------+----------+--------+ | Andy | NYC | 555 | <a href="/cdn-cgi/l/email-protection" cl ...

When a string begins with the "<" character, jQuery regex is unable to find a match

I am attempting to check if a string starts with the "<" character, but I am running into issues. The expression works perfectly fine on regex101.com, however, it fails when used in my personal files. When I input a backslash everything works as expect ...

Having a problem with file uploads in node.js using multer. The variables req.file and req.files are always coming

I am encountering an issue with uploading a file to my server, as both req.file and req.files are consistently undefined on my POST REST endpoint. The file I'm attempting to upload is a ".dat" file, and my expectation is to receive a JSON response. ...

Retrieve numerical data from the element and enclose it within a span tag

My goal was to indent a number, but the HTML generated from my CMS is making it difficult to target the number and apply a specific style. <div class="content"> <b>01. Header</b> Lorem ipsum dolor sit amet, consectetur adipisicing elit, ...

Is the AJAX $.ajax() function and setInterval() method activated only when a user is actively viewing the page?

The following code was created by me in order to refresh or reload the content within the div id='bitcoin_blocks_table', which only occurs when a user is actively on the website. I noticed that if no one is on the site and I return after 2 hours ...

retrieve the current image source URL using JavaScript

In the template below, I am looking to extract the current img src URL and utilize it in a fancybox button. For example, in the template provided, there are 3 images from https://farm6.staticflickr.com. When clicking on these images, the fancybox will ope ...

Has anyone created a modified version of jRails that is compatible with Rails 2.3 and jQuery 1.4?

We are revamping a website with Rails, and the current site heavily relies on jQuery v1.4 in its templates. We want to ensure that the existing scripts continue to function while also utilizing Rails' javascript helpers for our new scripts. While jRai ...

Revolutionary AJAX technology seamlessly updates and refreshes elements within every row or form on a webpage

<script type="text/javascript"> $(document).ready(function() { $("#submit<?php echo $resultshome['hskid']; ?>").click(function() { $.ajax({ type : "POST", url : "/scores/printPOST.php", data : { "subro ...

Leverage the power of PHP array values in your Javascript code

I am facing an issue where I cannot seem to run my javascript functions on a page after retrieving values from a local database using PHP. When the PHP code is included within my javascript, the function does not execute at all. However, if I separate the ...

Unable to ajax post on IE10

My struggles with getting ajax to function in IE10 continue. Despite various attempts and approaches, the result is always the same - an empty string. <html> <head> <script type="text/javascript" src="jquery-1-9-1.js"></script&g ...

How can you ensure that text inside a tag is styled as italic using font-style: italic and the !important keyword in HTML and CSS?

I've created an HTML site using chordpro.php generator, and the specific aspect related to this query is as follows: <div class="song"> <table border=0 cellpadding=0 cellspacing=0 class="songline"> <tr class="songlyricchord"><td& ...

Obtain the class attribute of a CSS element with whitespaces using PHP's XML/HTML

I'm currently facing an issue with the PHP XML DOM parser. When parsing HTML from the real world, I noticed that many elements have multiple CSS classes due to spaces in the 'class' attribute. However, when using getAttribute() on a DOMNode, ...

Add the AJAX response to the dropdown menu options

Currently in my project, I am utilizing Laravel as a backend. The scenario is such that once the corresponding page loads, it triggers an ajax request to fetch vehicle data which consists of vehicle model and plate number properties. My aim is to display t ...

Customize the Emotion Styled Material UI Tab Indicator Overwrite

Looking for a way to customize the appearance of tab indicators using Emotion styled components. I'm struggling to target nested classes in my code. Here's what I have so far: const StyledTabs = styled(Tabs)( { classes: { indicator: ...

Styling Rules for WebKit Browsers

Is there a method to apply a particular CSS style for a div based on whether the user is accessing the page from a Chrome browser on a Desktop or an Android device? .myDIV{ [if CHROME???] width: 280px; [if ANDROID???] width: 100%; } Seeking guidance on ...

Generate a text input field within a dropdown menu

Below is an example of my basic HTML code for a drop-down list: <span id="Div_List"> <label for="Gender">For:</label> <select name="Gender" id="Sex"> <option value="1">1000mtr</option> <option val ...

I am looking to insert a jQuery value or variable into the plugin options

How can I insert a jQuery value or variable into plugin options? This is my current script: $(document).ready(function() { // var bannerheight = 580; if ($(window).width() < 2100) { var bannerheight = 410; var opts = JSON.parse( ...

Retrieving the response data from a jQuery AJAX call prior to executing the success function

I have a system that relies on AJAX calls through jQuery for data retrieval. My goal is to capture all the received data along with the request details, without altering the existing $.ajax implementations, and forward it to another API for further analysi ...