Greek Geek GG Greek Geek GG - 6 months ago 10
HTML Question

HTML DOM get length of font style in a paragraph which has ID

This is what I've done

function myFunction() {
var x = document.links.length;
var y = document.images.length;
alert("Links = " + x + " , " + "Images = " + y);
}


Trying to get the length of different things in my site....

So far I've found how to get the length of the links and the images but I can't find ANY answer regarding font Styles...

I've found only this one

document.getElementById("myP").style.fontStyle = "italic";


in W3schools but is used only to change text into italic not getting the length of italics in a paragraph like I want for the last half hour....

for example

<p id="italic"> Lorem ipsum dolor sit amet, consectetur adipiscing elit.
<em>Donec at erat semper,</em> tempor magna sed, aliquet lorem.
Morbi iaculis libero sed <em>elementum</em> fermentum. <p>


of course there are more paragraphs with different IDs

Answer

If all you want to find is the number of <em> elements in the document as a whole:

var italicisedElements = document.getElementsByTagName('em').length;

var italicisedElements = document.getElementsByTagName('em').length;

document.getElementById('result').innerHTML = 'Number of &lt;em&gt; elements: ' + italicisedElements;
<p id="italic">Lorem ipsum dolor sit amet, consectetur adipiscing elit.
  <em>Donec at erat semper,</em> tempor magna sed, aliquet lorem. Morbi iaculis libero sed <em>elementum</em> fermentum.
</p>

<div id="result"></div>

To find the number of <em> elements within an element of a given id, such as id="italic":

var italicisedElements = document.querySelectorAll('#italic em').length;

var italicisedElements = document.querySelectorAll('#italic em').length;

document.getElementById('result').innerHTML = 'Number of &lt;em&gt; elements: ' + italicisedElements;
<p id="italic">Lorem ipsum dolor sit amet, consectetur adipiscing elit.
  <em>Donec at erat semper,</em> tempor magna sed, aliquet lorem. Morbi iaculis libero sed <em>elementum</em> fermentum.
</p>

<div id="result"></div>

To find all elements in the document whose CSS (whether in-line, with the style attribute, or set via CSS elsewhere) styles the text as italic:

var all = Array.from( document.querySelectorAll('*') ),
    italicisedElements = all.filter(function(node){
      return window.getComputedStyle(node).fontStyle === 'italic';
    }).length;

console.log(italicisedElements);

var all = Array.from(document.querySelectorAll('*')),
  italicisedElements = all.filter(function(node) {
    return window.getComputedStyle(node).fontStyle === 'italic';
  }).length;

document.getElementById('result').innerHTML = 'Number of &lt;em&gt; elements: ' + italicisedElements;
<p id="italic">Lorem ipsum dolor sit amet, consectetur adipiscing elit.
  <em>Donec at erat semper,</em> tempor magna sed, aliquet lorem. Morbi iaculis libero sed <em>elementum</em> fermentum.
</p>

<div id="result"></div>