CSS: Choose elements that have a single parent that matches the attribute selector

I'm relatively new to coding, so please bear with me if this seems like a silly question. I'm currently working on developing a general-purpose scraper to extract product data using the "schema.org/Product" HTML microdata.

Unfortunately, I encountered an issue during testing (on this specific page where the name was incorrectly set as "Electronics" due to conflicting schema elements from Breadcrumbs).

To start, I declared a variable to verify if the page contains an element with Product schema microdata.

var productMicrodata = document.querySelector('[itemscope][itemtype="https://schema.org/Product"], [itemscope][itemtype="http://schema.org/Product"]');

Next, my intention was to select all elements with the itemprop attribute, such as:

productMicrodata.querySelectorAll('[itemprop]');

The problem arises when I attempt to filter out elements with different ancestor schemas, such as Breadcrumbs and ListItem, which are still being included.

I assumed that by using the following logic:

productMicrodata.querySelectorAll(':not([itemscope]) [itemprop]');

I could avoid matching child elements with ancestor schemas (e.g. breadcrumbs), but to no avail.

I feel like I must be overlooking something obvious, but any guidance on how to correctly select elements with only one ancestor possessing the

itemtype="http://schema.org/Product"
attribute would be greatly appreciated.

EDIT: To clarify the location of the elements I wish to exclude, here's a visual representation of the DOM for the example page provided. My goal is to skip elements with any ancestor itemtype attributes.

EDIT 2: Corrected the use of parent to ancestor. Apologies for the oversight, as I'm still learning :|

EDIT 4/SOLUTION: I've identified a JavaScript-based solution utilizing the Element.closest() method. Here's an example:

let productMicrodata = document.querySelectorAll('[itemprop]');
let itemProp = {};

for (let i = 0; i < productMicrodata.length; i++) {
    if (productMicrodata[i].closest('[itemtype]').getAttribute('itemtype') === "http://schema.org/Product" || productMicrodata[i].closest('[itemtype]').getAttribute('itemtype') === "https://schema.org/Product") {
        itemProp[productMicrodata[i].getAttribute('itemprop')] = productMicrodata[i].textContent; 
    }
}

console.log(itemProp);

https://i.sstatic.net/P9HH2.png

Answer №1

:not([itemscope]) [itemprop] is defined as:

An element containing an itemprop attribute and having no ancestor with this attribute.

For example:

<div>
    <div itemprop>
        <div itemprop> <!-- this one -->
        </div>
    </div>
</div>

This structure would qualify because although the parent element contains the attribute, the grandparent does not.

To target only elements without matching ancestor attributes, you must use the child combinator:

:not([itemscope]) > [itemprop]

Answer №2

Any suggestions on how I can specifically target elements that only have the attribute

itemtype="http://schema.org/Product"
would be greatly valued.

When using attribute selectors, you can specify explicit values:

[myAttribute="myValue"]

Therefore, to accomplish this, you would use the following syntax:

var productMicrodata.querySelectorAll('[itemtype="http://schema.org/Product"]');

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

Disabling a button does not automatically shift the focus to the next element in the tab order

Is there a way to limit the number of times a button can be clicked using jQuery? For example, I want a button that can only be clicked three times before disabling itself automatically. test.html <div class="main"> <input class="one" type="t ...

Navigating between various links using the tab key can result in complications with pseudo-elements when using

When using Chrome, try clicking in the results pane and then hit tab to focus on this first link: http://jsfiddle.net/2q6c7c36/2/ Have you noticed how the contents of .box seem to "jump up" outside of its border? It seems that this issue is related to th ...

Customizing Navigation Color on Laravel Websites for Staging and Live Servers

I am seeking a solution to change the color of the Laravel navigation bar depending on whether it is the live or staging server. Our current setup involves testing code on a staging server before pushing it to the live server in production via Bitbucket. ...

Position the text alongside the thumbnail rather than in the center

In the current setup, my username text is positioned in the center of the view. I want to reconfigure it so that it displays directly to the right of the thumbnail. However, removing the alignItems: 'center', property from the item disrupts the e ...

How can we prevent the text from shifting when the border width is adjusted

I've run into an irritating issue. My left menu text keeps shifting when I expand the border using jQuery. I've tried various solutions to prevent the text from moving, but nothing seems to work. Any suggestions? Could it be a CSS problem with t ...

Second word in the textbox receiving attention

When I type in the text box, it always focuses on the second word instead of the first word. If I set Maxlength=1, it doesn't allow me to type. I have to press backspace before typing. Can anyone help me with this issue? Below is my code: <input ...

What could be causing my fixed header to disappear in Safari 5?

I am experiencing a strange issue with my fixed header on Safari 5 for iPad. The header disappears once it scrolls down to a certain point, even though it works fine in IE, Firefox, Chrome, and the latest version of Safari. Has anyone else encountered this ...

Verify record removal without a PHP click

My website features a navigation menu that streamlines the browsing experience: <form action="../"> <select onchange="window.open(this.options[this.selectedIndex].value,'_top')"> <option value="" selected="selected">Navigate< ...

Tracking the progress of reading position using Jquery within an article

Here is an example of a reading progress indicator where the width increases as you scroll down the page: http://jsfiddle.net/SnJXQ/61/ We want the progress bar width to start increasing when the article content div reaches the end of the article c ...

Normal version with background image and mobile version with background color

Seeking advice on how to optimize my website for mobile devices. I have two separate CSS files - one for the mobile version and one for the desktop version. Combining them in the head of my HTML file is causing issues, as the background style from the desk ...

The most efficient method for interacting with externally generated HTML in Rails

For my Rails page help documentation, I utilized the HelpNDoc help authoring tool to generate a folder containing HTML pages and additional folders for JavaScript, images, stylesheets, and libraries. Now I am seeking the most efficient way to integrate thi ...

Does CSS include a shadow child operator?

Did you know that Google Chrome has a special feature called the shadow descendant combinator /deep/? This unique combinator allows for the selection of elements within shadow nodes. body div {...} // this doesn't target descendant divs inside shadow ...

Difficulty integrating Bootstrap with JavaScript file in Visual Studio Code

I am attempting to incorporate a dynamic progress bar by utilizing Bootstrap's progressbar and creating a custom JavaScript file. The goal is to continuously adjust the width of the progress bar at regular intervals to give the appearance of a moving ...

Introduction beneath the photograph using the Bootstrap framework

I have a div with an SVG background image and I am attempting to override Bootstrap's responsive behavior so that content can be displayed over the background. The desired outcome is for the text "test" to appear on top of the background, rather than ...

"Utilizing jQuery to Trigger CSS3 Transform Animation Replays After a Set Number of Iterations

I currently have an animated image set up like this: <div class="image_for_sping"> <img src="/anyimage.png"> </div> The image has a style attribute added by jQuery which contains the following animation properties: animation: spin3 ...

Poorly positioned text displayed inline in HTML

My attempt to place a title in a div toolbar next to some images has hit a snag. The text is not aligning correctly; it should be positioned at the top of the toolbar, but it stubbornly remains at the bottom without budging. I wish for it to be vertically ...

Having trouble getting the Vue checkbox change event to work?

I am currently utilizing Vue to handle a function that is not triggering on the change event when a checkbox is checked. I am uncertain if the issue lies in the fact that I have placed it within the mounted lifecycle hook or if there is another underlying ...

I encounter issues with HTML input fields becoming unresponsive whenever I attempt to apply CSS filters in IE8 for stretching the background

When I wanted to stretch a background image on my website so that it always fills the available window area regardless of resolution, I initially used background-size:cover;. Unfortunately, Internet Explorer doesn't seem to support valid CSS, so I had ...

Is it possible to examine elements within Outlook?

Creating HTML emails can be quite the challenge, especially when trying to make them compatible with Outlook. Is there a method to inspect elements in Outlook similar to how we do on a browser's console? ...

Guide to creating a nested list using the jQuery :header selector

Here is the structure of my html: <h1 id="header1">H1</h1> <p>Lorem ipsum</p> <h2 id="header2">H2</h2> <p>lorem ipsum</p> <h2 id="header3">H2</h2> <p>lorem upsum</p ...