|
| 1 | +<!doctype html> |
| 2 | +<html lang="en"> |
| 3 | +<head> |
| 4 | + <meta charset="utf-8" /> |
| 5 | + <title> |
| 6 | + Exploring The Interplay Between HTML Entities And TextContent In JavaScript |
| 7 | + </title> |
| 8 | + |
| 9 | + <link rel="stylesheet" type="text/css" href="./demo.css" /> |
| 10 | +</head> |
| 11 | +<body> |
| 12 | + |
| 13 | + <h1> |
| 14 | + Exploring The Interplay Between HTML Entities And TextContent In JavaScript |
| 15 | + </h1> |
| 16 | + |
| 17 | + <p id="encoded"> |
| 18 | + <!-- Common HTML entities. --> |
| 19 | + < > " → |
| 20 | + <!-- Slightly smiling face emoji. --> |
| 21 | + 🙂 |
| 22 | + <!-- Frowning face. --> |
| 23 | + ☹️ |
| 24 | + </p> |
| 25 | + |
| 26 | + <input id="input" type="text" size="40" /> |
| 27 | + |
| 28 | + <script type="text/javascript" src="../../vendor/jquery/3.6.0/jquery-3.6.0.min.js"></script> |
| 29 | + <script type="text/javascript"> |
| 30 | + |
| 31 | + var encoded = $( "#encoded" ); |
| 32 | + var input = $( "#input" ); |
| 33 | + |
| 34 | + // Our encoded element contains text that we created using HTML entities; that |
| 35 | + // is, web-safe encodings that represent other values. When we then extract that |
| 36 | + // generated content, we get the RENDERED VALUE, not the ENCODED VALUE! |
| 37 | + var encodedValue = encoded |
| 38 | + .text() |
| 39 | + .replace( /\s+/g, " " ); // Cleaning up the white-space. |
| 40 | + ; |
| 41 | + |
| 42 | + // Echo the textContent in the Input and the Console. |
| 43 | + input.val( encodedValue ); |
| 44 | + console.log( ( "%c" + encodedValue ), "font-family: monospace ;" ); |
| 45 | + |
| 46 | + // And, just as a test, let's make sure the jQuery .text() method is actually |
| 47 | + // matching the raw .textProperty content. |
| 48 | + console.log( encoded.text() === encoded.prop( "textContent" ) ); |
| 49 | + |
| 50 | + </script> |
| 51 | + |
| 52 | +</body> |
| 53 | +</html> |
0 commit comments