4

My prerequisite is, that I work with just one DOM and use just the DOM API like getElementById or querySelector or event references. Is it in this case safe to use the following condition

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

to check if the event has been bubbled to the body of the document?

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

ceving
  • 21,900
  • 13
  • 104
  • 178

2 Answers2

4

Yes, this is safe. DOM objects aren't replaced by the browser, they're fairly stable objects.

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

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

This is not a direct answer since it has already been given but rather a reminder, in case you use jQ already in project. It might come useful to someone reading this cause it's shorter to write and fairly more powerful in ways you can use it.

Just a note, in jQuery, since 1.6 you can use is(). Lets say you have:

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

You can compare jq select result to another:

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

You can compare it to DOM object:

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

You can use it with callbacks cause it doesn't create new jq object:

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

You can use it on a set: (true if it matches at least one element in set):

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

Probably has a couple of other clever uses possible: API description

DanteTheSmith
  • 2,937
  • 1
  • 16
  • 31