var test1= document.getElementByI" />
var test1= document.getElementByI" />
var test1= document.getElementByI"/>

  issue when in html attribute

138 Views Asked by At

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

2

There are 2 best solutions below

0
Tom On BEST ANSWER

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>

0
Geekyvinayak On

In html a blank space mean a single break character meant browser render the html file it will collaps all the white spaces into single white space but &nbsp is a html entity that stands for a non-breaking space. It represents a space that will not be collapsed or wrapped by the browser.

Now i java-script if you compare two things it will convert it into whole string and then treat them to compare as   is only understandable by html as it is it's entity java-script treat it as general string and you will not get them equal...

const a = "&nbsp"; console.log(a)  // got &nbsp

const b = " "; console.log(b)  // got " "

for example if you put two space in a string and in another string only single string java-script will take them as different as on converting it to a string it will not match character by character .

let c = "hi  test" ; let d ="hi test"; console.log(a===b) // got false

as it will treat spaces also a character so it wont match.

if need more explanation do comment i'll try to elaborate.