Solution 1 :

You could do something like the following to get the child nodes instead.

var a = document.getElementsByTagName('a');
for (var i = 0; i < a.length; i++) {
  let node = a[i];
  let children = node.childNodes;
  for (child of children) {
    if (child.nodeType === 1) {
     node = child;
     break;
    }
  }
  var style = window.getComputedStyle(node, null).getPropertyValue('font-size');
  var fontSize = parseFloat(style);
  console.log(a[i].textContent + "  | font-size:" + fontSize);
  console.log("-----------");
}
a {
  font-size: 40px;
}

h2 {
  font-size: 20px;
}

p {
  font-size: 10px;
}
<a href="#">First test</a>
<a href="#">
  <h2> Second test</h2>
</a>
<a href="#">
  <p>Third Test</p>
</a>

Problem :

I’m looking for a solution that looks for all anchors tags in a HTML and get the text and the respective font-size.

For example:

<a href="#">First test</a>   
<a href="#"><h2> Second  test</h2></a>
<a href="#"><p>Third Test</p></a>

With the CSS:

a{
  font-size: 40px;
}    
h2{
  font-size: 20px;
}    
p{
  font-size: 10px;
}

Should output the respective font size. However, using this solution:

var a = document.getElementsByTagName('a');
for (var i= 0; i < a.length; ++i){
    var style    = window.getComputedStyle(a[i], null).getPropertyValue('font-size');
    var fontSize = parseFloat(style); 
    console.log(a[i].textContent + "  | font-size:" + fontSize);  
    console.log("-----------");    
}

I get always the first level font-size:

"First test  | font-size:40"
"-----------"
" Second  test  | font-size:40"
"-----------"
"Third Test  | font-size:40"
"-----------"

Check the jsfiddle

Comments

Comment posted by segFault

You are only grabbing the anchor tags which all have 40px font size…

Comment posted by Teemu

What did you expect to get? I mean the links have only a single rule setting the font-size in your CSS.

By

Leave a Reply

Your email address will not be published. Required fields are marked *