Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript get style character by character in an element

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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!

>Solution :

If it is only bolded elements, you could do this:

HTML:

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

JavaScript:

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

Essentially, what you are doing is you are printing all the <b> elements in the div.

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:

<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"));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading