Is it safe to compare DOM nodes with "==="?

My precondition is that I only work with one DOM and use only the DOM API, for example getElementByIdeither querySelectoror event. In this case, it is safe to use the following condition.

if (document.body === event.currentTarget) { }

to check if an event has occurred in a bubble in the body of the document?

I know this will not work with cloned objects. But I do not clone any objects myself. Does a DOM API object clone objects anywhere?

+4
source share
2 answers

Yes, it is safe. DOM objects are not replaced by the browser; they are fairly stable objects.

I myself often use WeakMaps to bind data to elements without problems ( example ).

+4

, , , jQ . -, , , , .

, jQuery, 1.6, is(). , :

<div id="parent">
    <p>drek</p>
    <p id="target">kmek</p>
    <div>mrr</div>
</div>

jq :

$("#target").is($("#target"));

DOM:

$("#target").is(document.getElementById("target"));

, jq:

$( "#target" ).click(function( event ) {
  var target = $( event.target );
  if ( target.is( "li" ) ) {
    target.css( "background-color", "red" );
  }
});

: (true, ):

$('#parent').children().is("p");

, : API

0

Source: https://habr.com/ru/post/1690382/


All Articles