Eli Algranti Eli Algranti - 4 months ago 14
Javascript Question

Safely finding if an element exists in jQuery

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:

  1. using jQuery

    I know there are alternatives to jQuery using "vanilla javascript", getElementById comes to mind, which returns
    if the element does not exist; but ...
    jQuery selectors are more powerful than
    and jQuery frees you from worrying whether the browser supports the functions.

  2. 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?


The jQuery constructor will do different things depending on the format of the input, but you can use the find method to make sure that it only uses the input as a selector (as long as the input is a string):

var q = $(document).find(selector);
if (q.length > 0) {
  // found something

You can also use a different starting point than the document element, if you want to limit the search to a part of the page.