JF-Mechs JF-Mechs - 7 months ago 30
Javascript Question

Check selector type jquery

I am trying to create a jQuery extension that has an options to pass a target value.

Here is a sample usage of the extension

//passed value : #target-element-id
$("<selector>").myFunction({ target: "#target-element-id" });
//target should return an "ID" selector type.


Is it possible to validate if passed value is an id, class selector or Is it possible to check what type of selector was used?

For those who are asking why would I need to check the selector type .

It is because I would like to do something like..

if (isId) {
goDance();
}
else if (isClass) {
goSing();
}

Answer

You can use String.prototype.split() with RegExp /\s+/ then .pop() on options.target to retrieve each part of selector string; pass result of .pop() to jQuery(), call .prop() with parameter "id" to check strict equality compared to Array.prototype.slice() with parameter 1 on result of .pop() to check for id, else selector is a className

function goDance() {
  console.log("id")
}

function goSing() {
  console.log("className")
}

(function($) {
  $.fn.myFunction = function(options) {
    var type = options.target.split(/\s+|>/).pop();
    if ($(type).prop("id") === type.slice(1)) {
      console.log("id", type)
    } else {
      console.log("class", type)
    }
  }
}(jQuery));

$("#div").myFunction({target:"#targetId>.targetClass1"}); // `goSing`
$("#div").myFunction({target:"body #targetId"}); // `goDance`
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="div"></div>
<div class="targetClass">target class</div>
<div id="targetId">target id<span class="targetClass1">target class 1</span></div>