0

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 null if the element does not exist; but ... jQuery selectors are more powerful than getElementById 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?

1
  • " jQuery selectors are more powerful than..." querySelectAll()?
    – PeeHaa
    Commented May 9, 2015 at 11:59

2 Answers 2

4

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.

1
  • 1
    Thanks for the education. This one will throw an exception if the input is not a valid expression. Commented May 9, 2015 at 12:32
2

jQuery selectors are more powerful than getElementById

Taking a chance of flying in the face of your jQuery requirement. :-)

You're looking for document.querySelector (find the first matching element) and document.querySelectorAll (find all matching elements). They accept the full range of CSS selectors, which on modern browsers is a very complete toolkit indeed. They're supported by all modern browsers, and also IE8. They do not instantiate elements, they purely look them up.

1
  • thanks good to know about this one. Javascript is not my forte. Commented May 9, 2015 at 12:32

Not the answer you're looking for? Browse other questions tagged or ask your own question.