Choose an item that does not have any offspring

I am facing an issue with a webpage that contains either of the following:

<span id='size'>33</span>

Or

<span id='size'>
    <b>33</b>
    <strike>32</strike>
</span>

I need to extract the value '33' in both scenarios. Is there a CSS selector that can achieve this? I attempted to use the following code for selecting #size without a sibling b or a b that is a sibling of #size:

document.querySelector('#size:not(>b), #size>b').innerText

However, I keep encountering an error- "Error: SYNTAX_ERR: DOM Exception 12"

As per the w3 Spec, only Simple Selectors are supported. The problem lies in the fact that the "greater-than sign" (U+003E, >) is considered part of the definition of Simple Selectors.

Answer №1

It's not possible using a standard CSS selector, but you can achieve it with some simple JavaScript:

let element = document.querySelector('#size');
let b = element.querySelector('b');
let text = b ? b.innerText : element.childNodes[0].nodeValue;

console.log(text);

Answer №2

If you are looking for meaningful content in the #size element, excluding whitespace (as there may be tabs and returns between tags), or if it's not present, then retrieve the significant text of its first child:

// Determining if text consists only of whitespace
function isWhitespace(text){
    return text.replace(/\s+/,'').length === 0;
}

// Retrieving immediate text content of an element without including its children's text
function getImmediateText(element){
    var text = '';

    // All nodes within an element can be accessed as descendants to cycle through.
    for(var i = 0; i < element.childNodes.length; i++){
        var node = element.childNodes[i];
        // Text nodes have nodeType 3
        if(node.nodeType === 3){
            text += node.nodeValue;
        }
    }

    return text;
}

function getFirstTextNode(element){
    var text = getImmediateText(element);

    // If the text contains only whitespace and has children, recursively retrieve the first child's text
    if(isWhitespace(text) && element.children.length > 0){
        return getFirstTextNode(element.children[0]);
    }
    // Otherwise, return the current text content 
    else {
        return text;
    }
}

Answer №3

Once we have CSS Level 4 selectors and the parent selector, using a simple selector will be possible. However, at the moment, this cannot be done directly.

If you want to find the first text node, one workaround is:

var text = document.getElementById('size').innerHTML.split(/<.*?>/)[0];

This method should only be used if you are familiar with the content of your #size element.

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

Unpredictable hue of text

Is it possible to fill text with a combination of 2-3 random colors? ...

Having trouble setting the backgroundImage in React?

Hi there! I'm in the process of crafting my portfolio website. My goal is to have a captivating background image on the main page, and once users navigate to other sections of the portfolio, I'd like the background to switch to a solid color. Alt ...

Deletion of an element with Reactjs upon clicking

A photo gallery consists of a collection of photos with corresponding delete buttons. Below is the HTML snippet for a gallery containing two images: <div> <div class="image"> <img src="URL1"> <button class="remove">X</ ...

Changing the CSS Border of Thumbnails

Take a look at this screenshot of a thumbnail grid. I need to reposition the gray border so that it sits below the price and is consistently aligned across all products. The challenge arises when product titles vary in length, causing the price to be posit ...

What is the best way to smoothly switch from one Font Awesome icon to another?

I am working on an HTML button with the following code: <button id="sidebar-toggle-button" class="btn btn-primary header-btn" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasExample&q ...

What are the steps to implement a personalized canvas in ThreeJS?

Struggling with creating a basic ThreeJS application that displays 3D text on the scene. The examples on the website are too complex for beginners like me. I'm finding it hard to make the scene appear without using tricks and I want to customize my ow ...

What is the specific use of the second app.css file in Laravel?

I'm currently delving into Laravel 8, and I'm perplexed by the role of Resources\css\app.css. While every other component in the Resources directory serves a clear function, the app.css file appears to be empty. Even when I attempt to a ...

Creating a custom backdrop for your kaboom.js webpage

I created a kaboom.js application and I'm having trouble setting a background for it. I've searched online extensively and attempted different methods on my own, but nothing seems to be working. (StackOverflow flagged my post as mostly code so I ...

Unusual Blank Space Found Beneath a Displayed Block Item

I've noticed some odd whitespace appearing under all my display: block elements within a meganavigation. Despite adding the code snippet below (which also determines column widths), I can't seem to pinpoint what's causing this issue. Wheneve ...

Creating uniform table column widths within a flex container with dynamic sizing

I am working on designing a navigation system for my website using a table inside a flexbox. I want to ensure that the table columns have equal width and can scale dynamically. Additionally, I aim to wrap the text in the data cells without changing the cel ...

What steps can be taken to create a curved bottom for the header section?

While I've seen this question asked before, I'm not satisfied with how the design has been implemented. Here is my desired look for the curved header I've experimented with border radius left and right, but the edges are excessively rounde ...

Adjust the background color of a non-selected Material-UI checkbox

Currently, I am working with a combination of React-Redux and Material-UI to style my project. Within this setup, I have a checkbox component that is placed on a toolbar with a blue background color (#295ED9). So far, I have successfully altered the color ...

What could be causing WebKit to fail in accurately redrawing this text?

I am experiencing a unique issue with the WebKit renderer. It seems that when a text node contains a descender or ascender that extends beyond the selection box of the text node, and the position of the text node changes, WebKit fails to repaint the correc ...

Using C# and Selenium to locate and click on an input element based on the text found in

I am attempting to click on an input button with dynamically created main identifiers. To achieve this, I am trying to click it based on the span information that follows. <span id="DYNAMIC" class="a-button a-button-primary pmts-button-input apx-compa ...

Changing text on a button with JavaScript toggle functionality: A step-by-step guide

I am looking to implement a feature where I can hide and show overflow content in a div. When I click on the expand button, it expands the content. However, I want this button to toggle and change text as well. Thank you! function descriptionHeightMo ...

Attach the button to the input tag so that they are always connected

While working on the layout for my webpage, I encountered an issue with an input area and a textarea that I wanted to clone. Everything was functioning correctly, however, I wanted the "+" button to remain attached to the input tag even when the screen siz ...

Enhance User Experience by Implementing Event Listeners for Changing Link Visibility Using mouseover and getElementsBy

I am new to JavaScript and struggling to find a solution. Despite searching online for fixes, none of the solutions I've found seem to work for me. I have spent hours troubleshooting the issue but I must be missing something crucial. Can someone plea ...

Run various CSS animations repeatedly

I recently created a captivating text fade-in, fade-out animation consisting of four lines. Each line elegantly appears one after the other, creating a mesmerizing effect. However, there's now a request to have these animations run in an infinite loop ...

Tips on eliminating the header section in SlickGrid?

Is there a way to remove the header row in SlickGrid using CSS? I know there isn't an API for it, but maybe some CSS tricks can do the job. Any suggestions? Check out this example: Calling all CSS experts! I'm looking for assistance in modifyin ...

Dynamic gallery with customizable features (HTML/CSS)

Seeking guidance on creating a seamless html/css gallery without any spacing between each gallery element. All elements are identical in size, housed as list items within a ul inside a div. Media queries have been established to adjust site and image siz ...