Choosing a parent element by the content of a nested child element: A step-by-step guide

I'm looking to target the "ytd-compact-link-renderer" element, which contains a nested "yt-formatted-string" tag with an id="label" and innerHTML of "Creator Studio".This nested tag is multiple levels deep within the structure.

The "ytd-compact-link-renderer" element shares its class name with other unwanted elements, so I need to selectively target it based on the content of its nested element. Selecting it using CSS seems unlikely, so how can I achieve this using JavaScript or jQuery?

https://i.sstatic.net/G5Kj7.jpg

<ytd-compact-link-renderer class="style-scope yt-multi-page-menu-section-renderer" compact-link-style="">

    <a id="endpoint" class="yt-simple-endpoint style-scope ytd-compact-link-renderer" tabindex="-1" href="/dashboard">
      <paper-item class="style-scope ytd-compact-link-renderer" role="option" tabindex="0" aria-disabled="false">


        <div class="content-icon style-scope ytd-compact-link-renderer">
          <yt-img-shadow height="40" width="40" class="style-scope ytd-compact-link-renderer" disable-upgrade="" hidden="">
          </yt-img-shadow>
          <yt-icon class="style-scope ytd-compact-link-renderer"><svg viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet" focusable="false" class="style-scope yt-icon" style="pointer-events: none; display: block; width: 100%; height: 100%;"><g class="style-scope yt-icon">
        <path d="M19.43 12.98c.04-.32.07-.64.07-.98s-.03-.66-.07-.98l2.11-1.65c.19-.15.24-.42.12-.64l-2-3.46c-.12-.22-.39-.3-.61-.22l-2.49 1c-.52-.4-1.08-.73-1.69-.98l-.38-2.65C14.46 2.18 14.25 2 14 2h-4c-.25 0-.46.18-.49.42l-.38 2.65c-.61.25-1.17.59-1.69.98l-2.49-1c-.23-.09-.49 0-.61.22l-2 3.46c-.13.22-.07.49.12.64l2.11 1.65c-.04.32-.07.65-.07.98s.03.66.07.98l-2.11 1.65c-.19.15-.24.42-.12.64l-2 3.46c.12.22.39.3.61.22l-2.49-1c.52.4...
      </g></svg>


  </yt-icon>
        </div>
        <yt-formatted-string id="label" class="style-scope ytd-compact-link-renderer">Creator Studio</yt-formatted-string>
        <yt-formatted-string id="subtitle" class="style-scope ytd-compact-link-renderer"></yt-formatted-string>
        <yt-icon id="right-icon" class="style-scope ytd-compact-link-renderer" disable-upgrade="" hidden="">
        </yt-icon>
        <yt-formatted-string id="secondary-text" class="style-scope ytd-compact-link-renderer"></yt-formatted-string>

  </paper-item>
    </a>
  </ytd-compact-link-renderer>

Answer №1

Create your own custom function and choose based on the content provided. This script will target elements that "contain" a specific text, it's not an exact match but rather a partial match that is case insensitive

jQuery.expr[':'].contains = function (a, i, m) {
    return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
};

var searchTerm = "Creator Studio"
var selectedElement = $('ytd-compact-link-renderer').find('yt-formatted-string:contains("'+searchTerm+'")');
selectedElement.doSomething();

Have a look at this example

If you require an exact match, utilize the following script

//define your function name
jQuery.expr[':'].containsOnly = function (a, i, m) {
    return jQuery(a).text().toUpperCase() == m[3].toUpperCase();
};

Answer №2

If you are utilizing Jquery, my recommendation would be to use

$("#label").parent().parent().parent().doStuff()
, although it may appear a bit cluttered. The first parent selector targets <paper-item>, the second selects <a>, and finally, the third selects
<ytd-compact-link-renderer>
. A cleaner alternative could be
$("#label").parent('ytd-compact-link-renderer').doStuff()
. For additional methods, check out this link.

Answer №3

If you're looking to target a specific element, consider using the following code snippet:

var selectedTag = $("#label:contains('Creator Studio')").closest('ytd-compact-link-renderer')

This piece of code will identify and return the ytd-compact-link-renderer tag. From there, you have full control over what actions you want to perform with the selectedTag variable.

Answer №4

I am interested in targeting the "ytd-compact-link-renderer" tag, which contains a nested "yt-formatted-string" tag with id="label" and the innerHTML set to "Creator studio".

It seems like you are looking to select the ytd-compact-link-renderer tag that includes a child element (not directly linked) yt-formatted-string with an id of label and the content inside is "Creator studio".

You can achieve this using jQuery with the methods has and contains

var element = $("ytd-compact-link-renderer:has(yt-formatted-string:contains('Creator Studio'))");

Check out the Demo below:

var element = $("ytd-compact-link-renderer:has(yt-formatted-string:contains('Creator Studio'))");

console.log(element.length); // Verify if the correct node is selected
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ytd-compact-link-renderer class="style-scope yt-multi-page-menu-section-renderer" compact-link-style="">

  <a id="endpoint" class="yt-simple-endpoint style-scope ytd-compact-link-renderer" tabindex="-1" href="/dashboard">
    <paper-item class="style-scope ytd-compact-link-renderer" role="option" tabindex="0" aria-disabled="false">


      <div class="content-icon style-scope ytd-compact-link-renderer">
        <yt-img-shadow height="40" width="40" class="style-scope ytd-compact-link-renderer" disable-upgrade="" hidden="">
        </yt-img-shadow>
        <yt-icon class="style-scope ytd-compact-link-renderer"><svg viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet" focusable="false" class="style-scope yt-icon" style="pointer-events: none; display: block; width: 100%; height: 100%;"><g class="style-scope yt-icon">
        <path d="M19.43 12.98c.04-.32.07-.64.07-.98s-.03-.66-.07-.98l2.11-1.65c.19-.15.24-.42.12-.64l-2-3.46c-.12-.22-.39-.3-.61-.22l-2.49 1c-.52-.4-1.08-.73-1.69-.98l-.38-2.65C14.46 2.18 14.25 2 14 2h-4c-.25 0-.46.18-.49.42l-.38 2.65c-.61.25-1.17.59-1.69.98l-2.49-1c-.23-.09-.49 0-.61.22l-2.05ur Link Has Been Truncated)

Answer №5

If you need to target the parent element of a specific element, you can use the closest() method in jQuery:

var label = $('yt-formatted-string#label:contains("Creator Studio")');
label.closest('ytd-compact-link-renderer').addClass('selected');

Here is a helpful example on jsFiddle

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

Uploading base64 arrays from AngularJS to a Node.js server: Allowing Access-Control-Origin

My current challenge involves sending an array of base64 strings from my Client Side (AngularJs) to my NodeJs Server. However, I've encountered a peculiar situation. When I attempt to send an object containing the base64 data along with other properti ...

Having trouble with the Safari search bar?

Hey there! I could really use some help with a search bar issue on my website kissoff.weebly.com. Everything works fine in IE, Chrome, Firefox, and Opera but it's not compatible with Safari because of the search bar. I'm trying to move the searc ...

What is the best way to enhance a map by incorporating a variable from Firebase?

I am currently facing an issue while trying to integrate a map into a specific key within my fire-store setup. Upon checking the console, I noticed that I am receiving an undefined error and an empty map is being added to fire-store. My goal is to upload ...

Change the class name on a RichFaces 4 component to utilize themeroller functionality

Before I dive in, let me mention that I have thoroughly gone through the following content: Stackoverflow:how can i remove the css classes from a richfaces component However, my concern lies with version 4 as opposed to v3.x which was discussed in the re ...

How can I align my logo on the website header separately from the menu tabs while keeping them on the same row?

Trying to vertically align a logo and headers' tabs in the same row can be quite challenging, especially when the logo is taller than the tabs. I've attempted different methods, including using padding to manually adjust the alignment, but it&apo ...

What is preventing my element from being positioned absolutely?

Struggling with setting up a CSS3 Menu and having trouble getting my ul to be positioned as absolute. I want the nav element to appear in the top left corner of the screen. Even though I've used the following code, the position properties seem not t ...

Replacing an Angular 2 application with a new webpage

I've been working on a project using Angular 2 and following this tutorial: Every time I run my api with npm run api on localhost:3000, the entire application gets replaced by another webpage. https://i.sstatic.net/5pIfX.png Here is my package.json ...

Auto resizing images with Bootstrap may not function correctly when placed in the left column

I have a standard 3-column layout with similar images in the left and right columns. When I resize the page, the right image becomes smaller but the left image does not. This causes the middle container to overflow past the left image. Here is the CSS for ...

Instead of displaying a preview of the file, the file upload with jQuery will now showcase the file link in a new window

I am currently working on a Jquery file upload project and I have decided not to use any plugins. My goal is to achieve this using Pure Jquery / JavaScript. Instead of previewing the file, I want to display a link (View) once the image or PDF is uploaded. ...

I am looking to loop through an array nested within a JSON object and display it in a table column using

Within my JSON data, there is an array that I need to loop through in <td> tags. The functionality I am working on involves creating a table based on user input. The user specifies the number of rows, input columns, and output columns. I have three a ...

Tips for refreshing the chosen item following a redirect to a different page

My current project involves creating an app with the use of ionic item-divider. A key feature is that when a user clicks on the list header, they are redirected to a new view where they can update and delete the selected item. However, I am facing a challe ...

LOGIN operation in Mongoose with Node.js fails due to a null value in

//register new user app.post('/signup', async function(req,res,next) { const saltRounds = 10; let password = req.body.password; let userEmailExist = await user.findOne({ email: req.body.email }); if(userEmailExist) return res.s ...

What is the best way to eliminate the content of an element using javascript/typescript?

The progress bar I'm working with looks like this: <progress class="progress is-small" value="20" max="100">20%</progress> My goal is to use javascript to remove value="20", resulting in: <progre ...

Harness the power of Vue.js by implementing plugin methods in your code

For my first attempt at building a SPA with Vue, I decided to re-use a few functions but encountered some issues. The error message "this.ExperienceToLevel is not a function" kept popping up and it left me puzzled. Furthermore, I'm contemplating if c ...

Find and choose the main div instead of the sub div in Robot Framework

I'm new to Robot Framework and working on test automation. I need to select the parent div, but the child div is always being clicked instead. Here's my current RF code: Wait and click element xpath: //div[contains(@class,'parent&a ...

libxml2 - deleting a child node without affecting its grandchildren

I'm working with libxml2 to parse HTML content and need to remove specific formatting tags such as <center>, while retaining their content (e.g. a hyperlink). This requires removing particular child nodes from my xmlNodeSet, while preserving th ...

arrange a div inside another div

I'm struggling to grasp the concept of how divs function in HTML. Below is a snippet of my HTML code: <div id="user_p"> <img src="img/pp/djbaptou.jpg"> <div class="followings"> djbaptou </br> Baptiste Arnaud </br> ...

Create HTML elements based on the information in a JSON object

My goal is to create span elements for each word in my subtitle text, which is stored in a JSON object. Here is the JSON data I am working with: var sub_info = [ {'start': 3.92, 'end': 6.84, 'words ...

The animation glitches out when attempting to update the color of the imported model

I'm facing an issue with a Blender model that has animation. After uploading it to the site, the animation works perfectly. However, I'm trying to change the body color of the model, and when I attempt to do so, the body stops animating and becom ...

Add a distinctive tooltip to the final element in a table row within a loop using JQuery

My challenge involves appending unique tooltips to the last item in a row of data, where each tooltip is specific to that particular row. However, when I add a new tooltip for the latest item, it ends up replacing the tooltips from previous rows. The desi ...