Home > Software design >  How can I display the current font H1 is using by JS
How can I display the current font H1 is using by JS

Time:01-06

I'm trying to make a tool for my wordpress site that will show the current styles of certain css selectors. Ie I would like to show what font (and later color) h1 should be displayed in.

I was thinking of using JS to do this and here is what I started with:

my HTML

<h1 id="harold">This is a H1 Heading</h1>

then in my functions.php to test I'm using this function:

/* Inline script printed out in the footer */
add_action('wp_footer', 'add_script_wp_footer');
function add_script_wp_footer() {
    ?>
        <script>
            var h1ID = document.getElementById('harold');
            console.log(h1ID.style.font);
            console.log("your font is: "   h1ID );
        </script>
    <?php
}

Ideally this should output helevtica your fontis: content of h1ID.

what I'm getting is <empty string> your font is [object HTMLHeadingElement]

I tried this as well:

        var h1ID = document.getElementById('harold');
        console.log("your font is: "   h1ID.style.font );

which just outputs your font is: .

I am doing something wrong, obviously, but is there a way I can query what font should be being displayed here? Ideally, I would rather just query by "h1", or "p" or etc, but I couldn't figure out how to do that.

CodePudding user response:

  1. The correct style attribute for the name of a font is fontFamily.
  2. HTMLElement.style returns just the inline element styles. To get any styles set through CSS, you need the computed style, returned via getComputedStyle(elem).
  3. To get the contents of any HTMLElement, you can use elem.innerHTML.

var h1ID = document.getElementById('harold');
console.log(getComputedStyle(h1ID).fontFamily);
console.log("your font is: "   h1ID.innerHTML);
h1
{
  font-family: Helvetica;
}
<h1 id="harold">This is a H1 Heading</h1>

CodePudding user response:

Use getComputedStyle to calculate the current CSS style value. In your case, an example is:

const element = document.getElementById('harold');
const fontFamily = window.getComputedStyle(element).fontFamily;
  •  Tags:  
  • Related