Skip to content Skip to sidebar Skip to footer

Is It Safe To Compare DOM Nodes With "==="?

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 co

Solution 1:

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).


Solution 2:

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


Post a Comment for "Is It Safe To Compare DOM Nodes With "==="?"