There are two DOM features available to accomplish what you are looking for, which does not require D3 at all. They will work for you, but will differ in complexity and flexibility.
Both Document and Element provide similar methods for retrieving elements based on specified criteria:
All these methods will return live HTMLCollection , which means that the collection of elements will be kept updated even after its first search. You can verify the existence of an element by HTMLCollection.item() collection using HTMLCollection.item() or .namedItem() , or if the collection contains only one element, take a look at .length .
var svg = document.getElementById("s");
<svg id="s"> <rect id="r"/> </svg>
There are also some properties available that provide access to live HTMLCollection or NodeList , which can for further workaround:
Note, however, that NodeList not guaranteed to live on their own; You will need to check the documentation. The following two methods return an inanimate NodeList and thus cannot be used for this purpose.
If you need the flexibility they provide, you can choose option 2.
The little-known and greatly understated MutationObserver interface comes in handy when you are interested in changes to the DOM. This is a more complex approach that can significantly increase flexibility.
You create a new MutationObserver that provides a callback that must be called every time a corresponding DOM change occurs. When you start the observer, you indicate what changes matter by defining the element - and sub-tree - and passing the MutationObserverInit configuration object. In the callback, you can freely respond to these changes in any way.
var svg = document.getElementById("s"); var rect = document.getElementById("r"); var observer = new MutationObserver(function(mutations) {
<svg id="s"> <rect id="r"/> </svg>
source share