Ways to choose tags that do not contain a particular tag within them

I am trying to utilize querySelectorAll to select all i elements that do not contain a font tag. The selector I attempted is:

  document.querySelectorAll('i > *:not(font)')
<i>
   <font color="008000">Here goes some text</font>
</i>
<br />
<i>Here goes another text</i>

Answer №1

The issue with the code is that it doesn't target all i elements that do not have a child font element as intended. Instead, it selects all children of i that are not font elements.

console.log([...document.querySelectorAll('i>*:not(font)')])
<i>
  <font color="008000">Here goes some text</font>
</i>
<br />
<i>Here goes another text</i>

To achieve the desired behavior, you should utilize the new :has() selector in CSS which is supported by all major browsers (except for Firefox where it may require a flag to be enabled):

console.log([...document.querySelectorAll('i:not(:has(> font))')])
<i>
  <font color="008000">Here goes some text</font>
</i>
<br />
<i>Here goes another text</i>

Answer №2

const elementsWithoutFont = document.querySelectorAll('i:not(:has(font))');

This should be successful.

Answer №3

By converting the NodeList returned by querySelectorAll() into an array using [...], we are able to easily remove DOM nodes using standard array methods:

const elements = [...document.querySelectorAll("i")]
  .filter((el) => !el.querySelector("font"));
  
console.log(elements);
<i><font color="008000">Here goes some text</font></i>
<br>
<i>Select me!</i>
<i>And <b>me too</b>!</i>
<i>However, <span><font>I am doubly nested, don't select me</font></span></i>

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

What is the best way to use multiple encoding types when sending data via a POST method in Node.js?

My current challenge involves sending a combination of name and description text data alongside a video file. Unfortunately, I've encountered an issue where I can only send either the video or the text, but not both simultaneously. Below is the code ...

React not displaying wrapped div

I am facing an issue with my render() function where the outer div is not rendering, but the inner ReactComponent is displaying. Here is a snippet of my code: return( <div style={{background: "black"}}> <[ReactComponent]> ...

"Key challenges arise when attempting to execute the node app.js script through the terminal due to various middleware compatibility

I'm a beginner with node.js and I've encountered an issue while trying to run my node app.js file after incorporating a new file named projects.js which contains the following JS code: exports.viewProject = function(req, res){ res.render(" ...

Why isn't my List<string> being retrieved from the MVC Controller in an $ajax request?

I am attempting to generate customized lists in my cshtml file through an ajax request. .ajax({ type: "GET", cache: false, url: "@Url.Action("getValidationLists")", contentType: "application/json", dataType: "json", ...

Setting an environment map in Three.js can replace the original texture on a model

I'm having trouble setting an environment map to an OBJ model. It seems like the appearance has changed drastically! In its usual view, it looks like this: https://i.sstatic.net/4VcIG.png But when I set the environment map, it transforms into this: ht ...

Is it possible to convert a leaflet marker into a nuxt-link function?

Recently, I started using nuxt and vue-leaflet to create an interactive map, even though I am quite new to it. This map consists of multiple markers representing different locations. The goal is for the respective page to open when a user clicks on a mark ...

Is it possible to verify .0 with regular expressions?

In my project, I have a field that requires whole numbers only. To validate this, I used a regex validation /^\d{1,3}$/ which successfully validates whole number entry and rejects decimal points starting from .1. However, I encountered an issue where ...

Tips for displaying a Bootstrap 5 popover triggered by a select option change event

I'm using a select box with 4 options, and I have set it up so that when the user clicks on one of the options, a Bootstrap 5 popover is triggered dynamically upon the change event. Fiddle: https://jsfiddle.net/mayursutariya93/qjeg5r9b/6/ Here' ...

Is there a way to eliminate the horizontal line in my Table design?

Is there a way to eliminate the horizontal line from the table? css, html <table border="1" style="width:100%; border-collapse: collapse"> <tr> <th>Prepared By:</th> <th>Released ...

Attempting to extract decibel levels from an audio file using JavaScript

I've been exploring the details provided here: Is there a way get something like decibel levels from an audio file and transform that information into a json array? However, when attempting to execute the JSBin snippet below, I encountered some conf ...

Ways to retrieve the neighboring element's value and modify it with the help of JavaScript or jQuery

I am encountering a problem with selecting an adjacent element and updating its value. My goal is to update the input value by clicking the minus or plus buttons. I have successfully retrieved all the buttons and iterated through them, adding onclick eve ...

Unable to retrieve data from the specified location using axios in a Nuxt application

I am experiencing an issue where axios is not following my GET path when the project is built, although it works fine in dev mode. I am using this code to fetch local .html files and inject them into my vue component. <template> <div> ...

Attempting to access an avatar image via an API, only to encounter an error message indicating that the avatar is not defined

userData is a function that retrieves user data from an API using getUserByChainAccount. The username required by getUserByChainAccount is dynamically fetched from buyer. I'm trying to access the avatar, but I keep encountering the error message Unha ...

Expanding the capabilities of search and replace in Javascript is imperative for enhancing its

I have developed a search and replace function. How can I enhance it by adding a comment or alert to describe the pattern and incorporating a functional input box? Any suggestions are welcome! <html> <head> <title> Search & Replace ...

Send a property as a string, then transform the string back into JavaScript

I am in the process of creating a versatile carousel that will cater to various conditions. Therefore, I need to set the "imageQuery" on my display page as a string and then make it work as executable javascript within my carousel. The query functions pr ...

How to set a background image with vue.js

My website design requires 70% of the page to be covered with an image, but the image is currently blank. I am using Vue.js as my frontend framework. Below is the code snippet that is resulting in a blank space: <script setup lang="ts"> imp ...

Count the start and end rows of a table within the <tfoot> using pdfHTML/iText 7

Currently, I am working on a project where I am developing a document generator that utilizes pdfHTML 3.0.3 and iText 7.1.14. The document includes a table displaying 'items'. It's worth noting that these item rows will likely span across mu ...

Tips for preserving the jquery inputmask after updating the DOM

It's difficult to explain, but here is a snippet showcasing the issue. (function() { var PhoneNumber = function() { this.name = ko.observable(); this.phone = ko.observable(); }; $('[data-mask="phone"]').inputmask({ mask ...

Troubleshooting CORS Problem with AWS CloudFront Signed Cookies

I encountered an issue while implementing cloudfront signed cookies. When trying to access '' from '', the CORS policy blocked it due to absence of the 'Access-Control-Allow-Origin' header. This problem arose after rest ...

Empty results in NgRx Parameterized Selector

Having trouble implementing a parameterized query in NgRx and receiving empty results. Check out the StackBlitz version of the code here: https://stackblitz.com/edit/ngrx-parameterized-query Update to Reducer Code export const userAdapter = createEntity ...