I have a dynamically created div with styled characters such as:
<div>Hello <b>J</b>oe</div>
and I am trying to figure out which characters are styled (in this case the J).
I have already tried window.getComputedStyle()
but I was unsuccessful in getting the style character by character.
Bigger 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 for your help!
3
Answers
If it is only bolded elements, you could do this:
HTML:
JavaScript:
Essentially, what you are doing is you are printing all the
<b>
elements in thediv
.However, the above applies to only bolded elements. If you would like to do it with more than just bolded elements, you can do this, but you need to know ALL the element tags. Like so:
HTML:
JavaScript:
Read the child nodes and you can look at the text, type, and node value. You can easily split it on characters to get the output.
so now to get the output
You can iterate the element’s child nodes (recursively) and accumulate a mapping of the characters to their parent elements. After collecting that list, you can map over it, deciding which types of elements are considered "styled", and convert those to boolean values.
Here’s a complete example that will work with the input you showed. It will also work with nested elements and it will allow you to modify which types of elements are the "styled" ones:
Code in TypeScript Playground