-8

What will be the impact, if we add some extra space in id or class in HTML.

Like if we write like this,

<div class="              class1" id="       id">This is a div</div>

Will the CSS or JS break?

Will there be any effect on class or id selection in JavaScript or CSS?

mplungjan
  • 169,008
  • 28
  • 173
  • 236

2 Answers2

0

A class can have space separated classeS and ID needs to be unique. You are not actually allowed spaces but the browser allows them anyway

So spaces in the className are handled, it is expected to have space delimited classes

The ID with spaces has the spaces as part of the ID - it is tolerated by the browser if you use the spaces in accessing it

var byCl = document.querySelector(".class1"),
byId = document.getElementById("id"),
byIdSpaces = document.getElementById("       id")
console.log(byCl); // ok
console.log(byId); // null
console.log(byIdSpaces); // ok
console.log("byCl",byCl.innerText)
console.log("byIdSpaces",byIdSpaces.innerText)
<div class="              class1" id="       id">This is a div</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

/*not working*/
console.log(document.getElementById("id"));
/*working*/
console.log(document.getElementById("       id"));
/*working*/
console.log(document.getElementsByClassName("class1")[0]);
/*working*/
console.log(document.querySelector('.class1'));
/*working*/
.class1{
color: red;
}
/*working*/
div[id='       id'] { 
  text-align: center;
}
/*not working*/
#id{
background-color: yellow;
}
/*not working*/
#       id{
font-size: 300%;
}
<div class="              class1" id="       id">This is a div</div>

Developers always make it work. :)

Utkarsh Dubey
  • 703
  • 11
  • 31