html

Escaping HTML

If you want to escape HTML symbols in JavaScript code you may think you should use escape() function, but not so fast. You can use this escape() for URL’s, but if you want to render HTML use the function below :

function escapeHTML(str){ return new Option(str).innerHTML }

-----

> escape("<div>")
'%3Cdiv%3E'

> escapeHTML("<div>")
'&lt;div&gt;'

WPress HTML: Updating <body> tag

In Word Press normally you can modify most of the part of the page via the Theme, but elements such as the <body> tag are inaccessible.

The solution is to use the wp_footer() hook and put a javascript code to update the element.
Here are the steps to do that :

  • Be very careful you are editing the Theme code and you can break something
  • Go to Appearance / Theme Editor
  • Select the Theme you are editing (Top-right)
  • Open function.php
  • Paste the code at the end of the file and save :
add_action("wp_footer", "body_onclick");

function body_onclick(){
    if(is_page("user-page")){ ?>
    <script>
        let body = document.getElementsByTagName("body");
        body[0].setAttribute("onclick", "alert('hi');"); 
    </script>
<?php }
}

Of course you can change the style instead of onclick.

In addition there are also other possible page selection criteria :

  • Only on archive pages: is_archive()
  • Only on the index of your blog: is_home()
  • Only on front page that may or may not be your blog index: is_front_page() 
  • etc…