What is the best way to choose an unidentified HTML element that contains text content?

In today's world, we often use CSS modules or other methods to hide classes and IDs. However, there are times when we need to select elements using JS selectors, and that can be a bit tricky.

Let's take an example. If we look at the home screen of YouTube, we might want to select the "Subscription" sidebar button. It seems like we could use the text value "Subscription" with a method like

document.getElementByValue("Subscription")
. Do you think this is the right approach, or is there a better way to achieve this?

How can we effectively select elements using JS selectors?

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

Here are some sources I found while researching:

Answer №1

The element highlighted in the screenshot is lacking uniqueness when it comes to classes. One approach could be to target all elements with similar classes and iterate through them to identify the one with the text "Subscription". The following code snippet retrieves the span element within the surrounding element:

document.querySelector("[aria-label='Subscriptions'] span")

Answer №2

For a different approach, consider locating the element with the span tag titled Subscriptions

let subscription = document.querySelector("span[title='Subscriptions']");
console.log(subscription.textContent);

Answer №3

Hey everyone, I managed to resolve my issue on my own. Huge shoutout to @Alexander Smirnov for the assistance!

I was able to utilize both of the selectors mentioned. I gained valuable insight from the discussion on the .parentNode concept, which proved to be very beneficial for me.

document.getElementsByClassName('style-scope ytd-mini-guide-renderer')[3]

or

document.querySelector("[aria-label='Subscriptions'] span").parentNode

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

The Google Software Development Kit has encountered a 403 error, indicating that the user has exceeded their

Currently, I am working on integrating the Google Developer SDK into my project to leverage the Google Translate functionality. While everything works smoothly when making a request using my access token obtained from the Google Developer Console, I keep e ...

Utilizing Kendo UI DateTimePicker to transfer chosen date to moment.js

Currently, I am working with a Kendo UI DateTimePicker that provides the selected date in the following format: Thu Dec 15 2016 23:23:30 GMT-0500 My objective is to pass this date into moment.js for extracting the day information like so: var momentDate ...

Directly insert an image into your webpage by uploading it from the input field without the need to go through the server

Can an image be uploaded directly from <input type="file" /> into an HTML page, for example through the use of Javascript, without needing to first save the image to the server? I am aware that AJAX can accomplish this, but if there is a way to ...

What is the best way to move the Grid upward when the above content is not visible?

Let me demonstrate what I have been working on. Currently, I am creating a weather application to explore the functionalities of https://material-ui.com/. I am attempting to prototype an animation inspired by Google Flights, which can be seen here: https: ...

How can I restrict the navigation buttons in FullCalendar to only allow viewing the current month and the next one?

I recently downloaded the FullCalendar plugin from Is there a way to disable the previous button so that only the current month is visible? Also, how can I limit the next button so that only one upcoming month is shown? In my header, I included this code ...

Calculate the time difference between time A and time B using DayJs

This is a common issue, but the unique aspect of this situation is as follows: I am attempting to calculate the hours between 12:00 (timeA) and 20:00 (timeB). A basic dayjs(timeA).diff(timeB, 'hours') yields 8 hours. The challenge arises when c ...

ReactJS encountering network errors when attempting to submit a form

As a fresh developer focusing on ReactJS, I have created a registration form using ReactJS on the FrontEnd, NodeJS on the BackEnd, and MySQL for the database. When attempting to submit the register form, testing the Backend on Postman yields successful re ...

Is there a way to achieve a XNOR-like response with necessary input?

I'm currently working with a form that looks like this: <form> <input type="text" name="input1"> <input type="text" name="input2"> <button type="submit"> ...

The backend function of an aspx page is failing to execute when triggered by a $.ajax request

Currently, I am facing an issue with a web form IndexPage.aspx. The script in this front-end code makes an ajax call to a code-behind function. Take a look at the code snippet below: $.ajax({ type: "POST", url: &apos ...

Custom control unable to display MP3 file

Hey, I came across this awesome button that I am really interested in using: https://css-tricks.com/making-pure-css-playpause-button/ I'm currently facing two issues with it. First, I can't seem to play the sound. I've placed the mp3 file ...

Feeling lost on the intricacies of threejs functionality

I have incorporated a sample code into this html/css document that utilizes a script to generate a 3D cube using three.js. Upon opening the HTML file, I am presented with a blank page in chrome displaying only, "canvas { width: 100%; height: 100% }" Belo ...

Updating existing text to create personalized HTML dropdown menus

I have designed a unique set of dropdowns by using divs and checkboxes instead of the traditional elements My goal is to dynamically change the 'select-wrapper--title' text (e.g. the first option) based on the selected option in the dropdown I ...

Is there a way to collect multiple optional phone numbers dynamically using DOM manipulation?

I have a piece of code here where I am looking to dynamically add additional phone numbers as an optional field. Can anyone help me figure out how to achieve this? <div class="col-12 row border my-2 py-2"> <di ...

Lazy Highcharts and Foundation clash when loading JavaScript

I'm currently utilizing lazy_high_charts along with foundation 4. Within my view, I have included <%= high_chart("my_id", @chart) %>, which produces the following: <section> <script type="text/javascript"> (function() { ...

Utilizing Selenium WebDriver with Python: Harnessing Test-Created Variables in JavaScript

How can I trigger the variable a, which I set to "Text" for testing purposes? ...

Maintain the grouping of elements within a div when printing in Internet Explorer 8

When printing in IE8, I'm facing an issue with keeping the "Table title" line on the same page as the <table>. Despite using page-break-inside:avoid;, there is still a page break between the table title and the actual table. My expectation is f ...

Tips on deleting CSS comments from a CSS file

Currently, I am utilizing nextjs + reactjs. My objective is to eliminate all CSS comments from my existing css file. Despite using next-purgecss in order to get rid of unnecessary CSS code, the comments are still persisting. What could be the reason behind ...

Triggering OnClick() more than once may result in the function failing to execute as intended

My dilemma involves a table of cells where clicking a cell triggers an event. I need to dynamically add cells, so I plan to call OnClick again on all rows. But when I do so for the second time, cells that have already had OnClick called twice stop firing a ...

Mapping Service by Google - Navigate from your current location to desired destination

I have a script that currently displays a route for either car or transit depending on the user's selection. I am looking to adapt this script to set the origin as the user's current location and route from there to a set latitudes and longitudes ...

Determine whether all elements in the array are false using Array.every()

Below is an example of an array: myArray = {firstValue: false, secondValue: false, thirdValue: true, forthValue: false}; The goal is to determine if every value in the array is false. If that condition is met, then perform a specific action. For instance ...