What is the best way to prevent "escaping" in the createTextElement method when using Javascript?

Check out the Jsfiddle demo

document.getElementById("container").appendChild(document.createTextNode(' '))
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet>
<div id="container" class="material-icons"></div>
<br>
<div class="material-icons">&#xe145;</div>

I am dealing with two <div> nodes.

&#xe145; represents the "plus sign" character code in the font.

Unfortunately, the execution of &#xe145; through Javascript doesn't seem to be functioning properly.

It appears that &#xe145; is being escaped by either createTextNode or appendChild...

If anyone has suggestions on how to prevent this escaping issue, I would appreciate it.

Answer №1

By creating a text node, you are bypassing the HTML parsing process that would normally recognize entity notation and display the corresponding content.

If you want to include special characters, you can use a JavaScript escape sequence like this:

document.getElementById("container").appendChild(document.createTextNode('\ue145'))

However, keep in mind that the string in the JavaScript code is interpreted based on JavaScript syntax rules, not HTML syntax rules.

Answer №2

&#xe145; represents an html entity in hexadecimal format

To implement, try using the .innerHTML method

var elem = document.getElementById("container");
elem.innerHTML = "&#xe145;";
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet>
<div id="container" class="material-icons"></div>
<br>
<div class="material-icons">&#xe145;</div>

Answer №3

Avoid using the innerHTML property as it can pose security risks.

If you want to steer clear of innerHTML, you can create a regular expression with str.replace to decode HTML entities in Strings.

function decode_html_entities(str) {
    return str.replace(/&(?:#x((?:[0-9a-f]{2}){1,2})|#(\d{1,3})|(amp));/ig, function () {
        if (arguments[1] || arguments[2])
            return String.fromCharCode(arguments[1] ? parseInt(arguments[1], 16) : parseInt(arguments[2], 10));
        var i,
            map = ['&']; // this matches &amp;, add more to the regexp for others
        for (i = 3; i < arguments.length; ++i)
            if (arguments[i]) return map[i-3];
    });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Clickable links and compliant W3C coding

Recently, I have encountered errors in the W3C validator due to the presence of "name" attributes in some <a> tags in my document. The validator flagged these attributes as obsolete. I am curious to know when and why this happened? Additionally, I n ...

Display just a fraction of a picture

Just recently, I had a surprising discovery when I right-clicked on the cross icon and noticed that the background image in the Tags section of the Ask Question page contained multiple icons beyond just the cross. Curious about how this was achieved, I sea ...

I am having trouble clicking the button in the popup dialog titled "Before you continue" on Google while using Selenium

I need help with clicking a button in dialog forms on Google. Here is the code I am using: @BeforeEach public void startDriver() throws InterruptedException { // Start Chrome browser System.setProperty("webdriver.chrome.driver", "C:& ...

Reload a tab on an ajax-enabled webpage

I am currently facing an issue with refreshing a tab instead of the entire page using Ajax. The specific tab in question involves deleting credit cards. When I select the credit card I want to delete and confirm, I use "window.location.reload();" to refres ...

Validating RSS Feeds with Javascript

Hey, I'm looking to replicate something like this: I want to verify RSS feeds before submitting a form. <form name="form1" id="form1"> <input type="text" name="url" type="text" id="url" /> <input type="submit" name="submit" id="bu ...

Error encountered when attempting to retrieve JSON data in JavaScript due to being undefined

A snippet of code that reads and writes JSON data is presented below: var info; $(function () { $.getJSON("data.json", function (d) { info = d; }); $('.btn').click(function () { info['c-type'] = $('#c- ...

CSS image cropping is a technique used to adjust the size

I have successfully created a grid of images with two columns, but I'm facing an issue with a portrait image disrupting the layout. I am looking for a way to adjust or "crop" the image so it matches the height of the landscape ones. I attempted to use ...

What benefits and drawbacks come with setting up JS libraries in resource files compared to package.json?

Configurations for JavaScript libraries such as Babel, Nyc, Eslint, and many others can be specified in resource files or within the package.json. For example, Babel can be set up in a .babelrc file or through a babel entry in the package.json. What are ...

Exploring the Differences Between NPM Jquery on the Client Side and Server

I'm still getting the hang of node and npm, so this question is more theoretical in nature. Recently, I decided to incorporate jQuery into my website by running npm install jquery, which placed a node_modules directory in my webpage's root along ...

Encountered a WebDriverException when attempting to capture a screenshot

While attempting to capture a screenshot from my Firefox browser, I encountered the following exception: org.openqa.selenium.WebDriverException: [Exception... "Data conversion failed because significant data would be lost" nsresult: "0x80460003 (NS_ERROR ...

Applying JavaScript to HTML - Implementing a function to only display an input statement when the "Yes" option is selected, otherwise keeping it hidden

I am currently delving into the world of JavaScript, aiming to comprehend its intricacies. With limited experience in this language, I have managed to successfully hide and unhide radio buttons based on user input. My next challenge lies in achieving a si ...

Mocha throwing 400 bad request error when making a post request with raw data

var expect=require('chai').expect; var http=require("http"); var request = require('request'); var env = require('./environment'); describe("Testing Callflow Functionality", function(done) { //this.timeout(15000); it("Tes ...

Calculate the sum of all values listed in a PHP table

I have implemented a pre-defined PHP inventory manager, and the data for sales is stored in the following format: [{"product_id":"8","total_number":"70","selling_price":"110"}] In order to display these values in a table, I am using the code below: $sub ...

Choosing the selected option in AngularJS

I am facing a frustrating issue with understanding how AngularJS manages select option values and selections. I have a basic item that I pass to a modal window, which includes a template_id. Additionally, I have a list of templates with names and ids, and ...

Using jQuery to send LocalStorage data to an email address with the help of PHP

Currently, I am in the process of developing a basic eCommerce/checkout system. My goal is to utilize localStorage data and transfer it to PHP using jQuery or any other method that is convenient. However, when I attempted to send the email, I only received ...

Error: The function execute_script() is expecting between one and two arguments, however three arguments were provided

While attempting to utilize the Selenium method execute_script() in an automated UI test script, I encountered a type error. The error message indicates that there are too many arguments being passed. TypeError: execute_script() takes from 1 to 2 positiona ...

Stop automatic resizing on mobile device after postback

Encountered an issue with a website I'm currently developing. It's not causing any problems, but I want to enhance the user experience. My aim is to maintain the zoom levels of mobile devices after a postback. To provide more context, there is a ...

The Dragula NPM package appears to be functioning smoothly during development environments, yet encounters issues when transitioning to the

I have developed a sophisticated drag and drop feature using React 15 and Dragula 3.7.2. However, when I bundle my Application for production, the drag and drop functionality ceases to work properly. I am only able to lift up a single element but cannot fi ...

Exploring TypeScript: Understanding how to define Object types with variable properties names

Having an issue with a React + TypeScript challenge that isn't causing my app to crash, but I still want to resolve this lingering doubt! It's more of a query than a problem! My goal is to set the property names of an object dynamically using va ...

What is causing the lack of response in the select box on Mac Chrome when I try to click on it?

Similar Question: JQuery function doesn't work on Chrome on Mac, but works on Chrome on Win 7 and all other browsers I am encountering an issue with a select-option list <div class="social-option"> <select name="hex_theme_options[soc ...