Ways to extract a collection of values using a designated CSS Selector

Is there a way to quickly retrieve a list of values from a specific CSS selector?

I am interested in extracting text enclosed in <strong> tags only. Currently, I am using :

document.querySelectorAll("p > strong")

However, the result I get is a Node list...

NodeList(101) [strong, strong, strong, strong, strong, strong, strong, strong, strong,...]

I have been trying to access the innerText like this:

document.querySelectorAll("p > strong")[1].innerText

Is there a way to extract all the targeted text values into a list at once?

Answer №1

Utilize the spread operator to convert it into an array and then apply the map method to extract the necessary information.

var array = [...document.querySelectorAll("p > strong")].map(a=>a.innerText);

console.log(array);
<p><strong>I</strong></p>
<p><strong>heart</strong></p>
<p><strong>To</strong></p>
<p><strong>Fart</strong></p>

Answer №2

When iterating over the nodeList in your code, it functions correctly

I prefer using textContent as it is more standardized

const strong = document.querySelectorAll("p > strong")
const texts = []
for (let i = 0; i< strong.length;i++) texts.push(strong[i].textContent)
console.log(texts)
<p>Here is some <strong>text</strong> and some <strong>more text</strong></p>

Alternatively, you can map the nodelist after converting it to an array using spread syntax

const texts = [...document.querySelectorAll("p > strong")]
  .map(({textContent}) => textContent)
console.log(texts)
<p>Here is some <strong>text</strong> and some <strong>more text</strong></p>

If needed, here is a solution using jQuery

const texts = $("p strong").map((_,e) => e.textContent).get();
console.log(texts)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<p>Here is some <strong>text</strong> and some <strong>more text</strong></p>

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 transfer properties from one object to another in Angular?

Explore the code snippet provided below: const a={type:"apple"}; const b={type:"banana", color:"yellow"}; const c = Object.assign(a,b); //result: c={type:"banana", color:"yellow"} //desired outcome: {type:"banana"} What modifications can be made to reach ...

Learn how to showcase information stored in a JSON file within a list format and how to retrieve specific elements within a JavaScript object

I am struggling with populating a list in my Vue 3 app using a validated JSON file containing all the languages of the world. My lack of experience is making it difficult for me to access the inner parts of an object, so I need some guidance on that. JSON ...

Numerous Radio Buttons

I am currently working on creating a quiz similar to those found on Buzzfeed and Zimbio. I apologize if this question has been asked before, but despite my efforts in searching, I have not been able to find the answer I am looking for. In this quiz, partic ...

Center align the message 'No file chosen' in the File Upload control horizontally

I am facing an issue with a file upload control that I have implemented. The code is provided below: <div class="row"> <div class="col-md-12"> <div class="alert alert-warning normal-text hide" role="alert" id="ImportErro ...

jQuery Autocomplete API Issue: Undefined

I've been attempting to implement a basic text box using the jQuery API from DevBridge. I followed instructions in this video tutorial to create my code. However, despite properly declaring scripts before the JS code and ensuring proper mappings, I&a ...

Ways to update a ViewComponent using Ajax in Asp.net Core 3.1

How can I make FavoriteComponent refresh when the "a" tag is clicked? Html : <div id="favorite-user"> @await Component.InvokeAsync("FavoriteComponent") </div> Action Html : <a id="add-fav" onclick="addfavorite('@pr ...

tips for modifying html element attributes using angular

I am working with an element that is automatically generated through an API call as <a target="_blank" href="http://www.work.com/reward"><b class="orange tdu">My Work History</b></a> and now I want to modify it like <a ng-cl ...

Unable to utilize ng-Bootstrap datepicker

I recently cloned the quickstart project from the tour of heroes guide on Angular's official website, and I wanted to incorporate the ng-Bootstrap datepicker. However, I encountered some issues with its functionality. Below are the key components of m ...

Guide to customizing WordPress header menu buttons with CSS, excluding a specific button

I need help with custom CSS for my WordPress site. I want to apply a hover effect to all menu buttons except for the "Contact" button, which already has its own styling. The CSS code adds a growing line beneath the hovered menu item and a static line unde ...

Organizing elements in JavaScript

By utilizing d3.nest, I've organized this list through element grouping from another list. array = [ {key: "6S", values: [{Id: "1234a", ECTS: 3}, {Id: "1234b", ECTS: 3}]}, {key: "7S", values: [{Id: "1534a", E ...

I need help using i18N to translate the SELECT option in my VUE3 project. Can someone guide me

<n-select v-model:value="value" :options="options" /> options: [ { label: "Every Person", value: 'file', }, { label: 'Drive My Vehicle', ...

What steps should I take to fix my responsive media query?

I am currently working on fixing some responsive issues on my WordPress website. Previously, in mobile view, it looked like this: https://i.stack.imgur.com/vpvHy.jpg After adding the following code to the CSS of my child theme: @media only screen a ...

Label for the checkbox is covering other content on the screen in 1024 x 768

Here is the JSP code snippet: <h:field path="configuredChannels" required="true" code="admin.menu.channels"> <div class="row-fluid" data-channel-checkboxes="#"> <form:checkboxes element="div class=&apos ...

Using Postgres array or JSON to display separate Bootstrap badges within an HTML document

Here is a snapshot from my live server: https://i.sstatic.net/sq83x.png In the image attached, I have been working on extracting information from arrays and JSON using Bootstrap. My goal is to display each value from the array or JSON in separate badges. ...

What is the best way to eliminate or substitute Unicode Characters in Node.js 16?

Currently, I have a file that is being read into a JSON Object. { "city": "Delicias", "address": "FRANCISCO DOMÍN\u0002GUEZ 9" } We are using this address to send it to the Google Maps API in order to ...

Javascript function fails to run smoothly during rapidscrolling

I'm facing an issue with my JavaScript code that adjusts the transparency of the navigation bar while scrolling. It works perfectly when scrolling slowly, but when the scrolling speed is fast, it seems like the function is not triggered and the navbar ...

The lodash debounce function is being triggered multiple times instead of just once, causing issues with my react hooks in a react native environment

Currently, I am implementing a search feature for multiple objects in an array that triggers onChange of the text Input. To optimize this process, we need to incorporate a debouncing function to prevent unnecessary API calls to the search function. Howeve ...

Connecting images and text from a distance

After days of researching this topic, I have not found any solutions that align exactly with what I am trying to achieve. I believe it should be a simple task using just HTML and CSS, but I seem to be facing some difficulties. Initially, my goal was to ma ...

Converting a function to an ES6 class-based style

Hello, I am new to ES6 and eventEmitter. I have created a module in Node.js with an event-based style and now I am trying to convert it to ES6 class style. This is my code: // eventStyle.js const events = require('events'); const util = require ...

Erase Photo from Server by Simply Clicking on the Remove Button NodeJS (And Removing the Image Title from the Database)

I have a button that successfully deletes an image name from a mySQL table. However, I also want it to delete the actual image from the server. Below is the code snippet from my index.js: document.querySelector('table tbody').addEventListener(&a ...