Search code examples
javascripthtmlspacehtml-entities

  issue when in html attribute


Code first.

<div data-a="a b" data-b="a&nbsp;b" id="test"></div>
<div data-a="a<b" data-b="a&lt;b" id="test2"></div>
var test1= document.getElementById('test');

var test1_a= test.getAttribute('data-a');
var test1_b=test.getAttribute('data-b');

// data-a="a b" data-b="a&nbsp;b"
console.log('1:',test1_a===test1_b); // got false;



var test2= document.getElementById('test2');

var test2_a= test2.getAttribute('data-a');
var test2_b=test2.getAttribute('data-b');
// data-a="a<b" data-b="a&lt;b"
console.log('2:',test2_a===test2_b); // got true;

Question: why &nbsp; and &lt; are different in html attribute?

Online run able example. https://codepen.io/qinbx/pen/eYPqBGQ


Solution

  • In your case, the problem comes from the data-a attribute, not the HTML Entities.

    The 'space' character is different from the 'non-breaking space' character.

    See this list of HTML entities and note that the space character can be written using its entity number &#32;.

    I updated your example using the 'non breaking space' character (alt + 255) :

    var test1= document.getElementById('test');
    
    var test1_a= test.getAttribute('data-a');
    var test1_b=test.getAttribute('data-b');
    
    console.log('1:',test1_a===test1_b);
    
    var test2= document.getElementById('test2');
    
    var test2_a= test2.getAttribute('data-a');
    var test2_b=test2.getAttribute('data-b');
    
    console.log('2:',test2_a===test2_b);
    <!-- a space b -->
    <div data-a="a b" data-b="a&#32;b" id="test"></div>
    <!-- a non-breaking space b (alt + 255) -->
    <div data-a="a b" data-b="a&nbsp;b" id="test2"></div>