Stackoverflow already has an answer for how to check if an element exists in jQuery.
When using jQuery the answer, with small variations, basically boils down to "send the name of the element to the magic jQuery function and check whether something is returned":
if ($('elementName')[0]) ...
The problem with this approach is that if the jQuery function receives an html fragment it will "instantiate" the html (javascript included) and return the node that represents it. This means the jQuery function can only be used with trusted input, least you expose your site to a DOM based XSS like the one reported not long ago for wordpress. My question is:
Is there a way to use jQuery to check whether an element exist with untrusted input?
The important parts of the question are:
- using jQuery
I know there are alternatives to jQuery using "vanilla javascript", getElementById comes to mind, which returnsnull
if the element does not exist; but ... jQuery selectors are more powerful thangetElementById
and jQuery frees you from worrying whether the browser supports the functions. - with untrusted input
You can obviously use regex or html encode to sanitize the input but you still have to worry about browser support for your sanitizing code.
I.e. my question is basically is there a way to prevent jQuery from creating new DOM objects and just say whether the input to the jQuery function maps to an existing DOM object?