Retrieve the individual character styles within an element using JavaScript

I'm currently dealing with a dynamically created div that features styled characters like:

<div>Hello <b>J</b>oe</div>
and my goal is to identify which characters are styled (in this case, the letter J).

I've already attempted using window.getComputedStyle() but I haven't been able to extract the style character by character.

Here's a larger example:

<div id="testing">H<b>i</b> I <b>a</b>m b<b>o</b>b</div>

Expected output: getDivStyle("testing") =>

H: false
i: true

I: false

a: true
m: false

B: false
o: true
b: false

Thank you in advance for your assistance!

Answer №1

To highlight only certain elements, you can follow this approach:

HTML:

<div id="my-div">Hello <b>J</b>oe</div>

JavaScript:

console.log(document.getElementById("my-div").querySelectorAll("b"));

This code snippet retrieves and logs all the <b> elements within the specified div.
However, if you want to target more than just bolded elements, you can do so by specifying all the element tags you want to include like this:

HTML:

<div id="my-div"><i>Hello</i> <b>J</b>oe</div>

JavaScript:

console.log(document.getElementById("my-div").querySelectorAll("b"), document.getElementById("my-div").querySelectorAll("i"));

Answer №2

Inspect the child nodes to analyze their text, type, and node value. By breaking it down into characters, you can easily manipulate the data.

const nodes = document.querySelector("#testing").childNodes;
nodes.forEach(node => {
  console.log(node.textContent, node.nodeType === Node.ELEMENT_NODE, node.nodeName);
});
<div id="testing">H<b>i</b> I <b>a</b>m b<b>o</b>b</div>

To obtain the desired output:

const nodes = document.querySelector("#testing").childNodes;
const result = Array.from(nodes).flatMap(node => {
  const isElem = node.nodeType === Node.ELEMENT_NODE;  
  return Array.from(node.textContent).map(char => char === ' ' ? '' : `${char}: ${isElem}`);
});

console.log(result.join("\n"));
<div id="testing">H<b>i</b> I <b>a</b>m b<b>o</b>b</div>

Answer №3

To collect information about the characters in an element and their parent elements, iterate through the child nodes recursively. Once you have gathered this data, you can then determine which elements are considered "styled" and convert them into boolean values.

Here is a comprehensive example that can handle nested elements and allows for customization of what constitutes a "styled" element:

View Code in TypeScript Playground

/** @returns an array of [character, parent element] */
function createTextMapping(element, memo = []) {
  for (const node of element.childNodes) {
    switch (node.nodeType) {
      case Node.TEXT_NODE: {
        for (const str of node.data) {
          memo.push([str, element]);
        }
        break;
      }
      case Node.ELEMENT_NODE: {
        createTextMapping(node, memo);
        break;
      }
      default: throw new Error("Unexpected node type");
    }
  }
  return memo;
}

// Define which elemnet tag names are considered "styled":
const styledElementTagNames = new Set([
  "B",
  "EM",
  "I",
  "STRONG",
  // etc.
]);

const targetElement = document.getElementById("testing");

const mapping = createTextMapping(targetElement);

const results = mapping
  .filter(([str]) => str.trim().length > 0) // Remove whitespace
  .map(([str, elm]) => [str, styledElementTagNames.has(elm.tagName)]); // Validate parent elements

for (const [str, valid] of results) {
  console.log(`${str}:`, valid);
}
body { font-family: sans-serif; }
<div id="testing">H<b>i</b> I <b>a</b>m b<b>o</b>b</div>

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 change the font size in HTML?

https://i.sstatic.net/IjLvn.png After carefully analyzing the image provided, I encountered an issue while attempting to incorporate the code display:block. However, no changes were reflected. Can you identify what may be causing this discrepancy in my te ...

Executing a function within the same file is referred to as intra-file testing

I have two functions where one calls the other and the other returns a value, but I am struggling to get the test to work effectively. When using expect(x).toHaveBeenCalledWith(someParams);, it requires a spy to be used. However, I am unsure of how to spy ...

Unable to adjust image opacity using jQuery

I am attempting to change the opacity of an image based on a boolean flag. The image should have reduced opacity when the var pauseDisabled = true, and return to full opacity when pauseDisabled = false. To demonstrate this, I have created a fiddle below. ...

Bundling and minifying Angular2 assets

In the world of ASP.NET (or gulp), bundling and minification are taken care of. However, a different issue arises when following Angular2 tutorials: the view HTML is typically embedded within the component itself. Fortunately, there is a way to separate th ...

What is the best way to increase the height of a div up to a specific point before allowing it to scroll?

Is there a way to make a div expand to fit its contents up to 250px and then scroll if necessary? I attempted using the following CSS: text-overflow: ellipsis; max-height: 250px; overflow-y: scroll; However, this solution doesn't achieve the desired ...

Exploring the jungle. Cursor acting strange while dragging

I am currently working on implementing drag-and-drop functionality in my project, utilizing slip.js from slip.js. To enhance the cursor during dragging, I have assigned class="draggable" to each draggable <tr>. The CSS code for this class is: .drag ...

Showing the loading screen while waiting for the static Next.js app to load

Looking for a way to implement a loading screen right before the entire static page finishes loading? I'm currently utilizing modules:export to create my static page, but struggling to listen to the window load event since NextJs has already loaded th ...

jQ identifying children with particular styling attributes

I am attempting to locate a child element that meets the following conditions: CSS visibility set to visible and CSS class assigned as foo There will always be only one element that meets these criteria at any given time var visibleBox = $('#parentE ...

Values in Local Storage are not located upon first attempt, but after a reload they function properly

import {useEffect} from 'react'; import {useRouter} from 'next/router'; const AuthenticationGuard=props=>{ const {children,fallback} = props; const auth = useAuth(); const router=useRouter(); useEffect(()=>{ if(!r ...

Header element not keeping the navbar at the bottom

My goal is to attach this navigation bar to the bottom of a header, but it's sticking to the top instead. I want the navigation to remain at the bottom of the header even when the user scrolls down. Currently, both the header and navigation are set t ...

Is it possible to divide a column in an HTML table into two separate

I am currently working with an array of elements that I need to iterate over. For each element, I create a <td></td> tag. When dealing with 10 elements, it results in a table with one column and 10 rows. Is there a method, using either HTML o ...

Navigation through dots on a single page

Having an issue with my dot navigation and anchor links placement. I want the anchors to be vertically centered in the middle of the section, regardless of window size. Here's what I'm aiming for : For larger windows : https://i.sstatic.net/pK4 ...

Having trouble resolving a component from a component library while utilizing NPM link

My React application is set up with Create React App and a separate component library. I'm currently experimenting with using 'npm link' to test changes in the component library directly on my local machine. To achieve this, I first run &ap ...

Issue with Firebase Cloud function not terminating despite receiving a 204 response code

Currently, I am developing a cloud function to manage server operations for a gaming panel. Everything seems to be functioning correctly except that after the request is completed, it fails to trigger the expected "data", "end", or "closed" events which ...

Applying a translucent layer of color to a jpeg image to create a subtle background effect

I am attempting to create a semi-transparent, solid background color on top of an <img> tag, while still showing the original image underneath at the same ratio and size. Below is a snippet of the code I am working with (let me know if you need more ...

Delay the next loop iteration until receiving an HTTP request

I have a task where I am collecting YouTube video IDs and storing them in an array. Then, I am looping through each video ID to determine the size of that ID's thumbnail image. My challenge now is making sure my loop waits for the HTTP request to fini ...

If the number exceeds 1, then proceed with this action

I currently have a variable called countTicked, which holds an integer representing the number of relatedBoxes present on the page. I am in need of an if statement that will perform certain actions when the value stored in countTicked exceeds 1. if (!$(c ...

Are there any open source libraries in jQuery or HTML that can be used for creating av

I have been searching extensively for an open source avatar library that can perform basic functions like choosing gender, eyes, and clothing. It was surprising to me that I couldn't find any open source framework for avatars on the web, especially c ...

Steps for Adding a JSON Array into an Object in Angular

Here is a JSON Array that I have: 0: {name: "Jan", value: 12} 1: {name: "Mar", value: 14} 2: {name: "Feb", value: 11} 3: {name: "Apr", value: 10} 4: {name: "May", value: 14} 5: {name: "Jun", value ...

Having difficulties injecting a Service into a TypeScript Controller

I recently started working with TypeScript and I created a controller where I need to inject a service in order to use its methods. However, I am facing an issue where I am unable to access the service functions and encountering an error. Error TypeError ...