HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

jQuery selector function in JavaScript

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
selectorjqueryfunctionjavascript

Problem

I've reproduced the jQuery selector function in JavaScript.

Here are the two rules that come with this function:

  • You may not use any JavaScript libraries.



  • document.querySelector/document.querySelectorAll may not be used.



```
var $ = function (selector) {
var elements = [];
// get starting index position of id / class
var classPosition = selector.split('').indexOf(".");
var idPosition = selector.split('').indexOf("#");
// split selector into array
var selectorArray = selector.split("");

if ( classPosition === -1 && idPosition === -1){
// simply set equal elements to DOM object with the specific tag name
elements = document.getElementsByTagName(selector);

}else if (classPosition > -1 && idPosition === -1 ){
if (classPosition === 0) {
selectorArray.shift();
// array elements returns DOM object with the desired class name
elements = document.getElementsByClassName(selectorArray.join(""));
}else {

// array elements returns DOM object with the matching class

var tagElem = selectorArray.slice(0,classPosition).join("");

var className = selectorArray.slice(classPosition + 1,selectorArray.length).join("");

var tagElemCollection = document.getElementsByTagName(tagElem);
// iterate through DOM object check if class match match className
for (var i = 0; i -1 && classPosition === -1){
if (idPosition === 0) {
// array elements returns DOM object if an id is passed in
selectorArray.shift();
elements.push(document.getElementById(selectorArray.join("")));

}else {

var tagElem = selectorArray.slice(0,idPosition).join("");

var idName = selectorArray.slice(idPosition + 1,selectorArray.length).join("");

var tagElemCollection = document.getElementsByTagName(tagElem);

Solution

First off, you have a bug. On the line if (tagElemCollection[i].id != "") {, you used the != operator instead of the !== operator. This line should be changed to if (tagElemCollection[i].id !== "") {.

Secondly, you have some spacing inconsistencies. For example, you wrote }else { in some places, and }else{ in others, when it should be } else {, and/or } else if {. You also have stuff like this, (var e = 0;e < eachId.length;e++), or this (var p=0; p < ClassMatch.length; p++), that can both be typed like this: (var name = ...; name ... value; name...). Try to find inconsistencies like these and change them.

Finally, you have some indentation issues. The general style is that lines should be indented by one tab, or four spaces if they're in a if/else if/else/function/etc block.

Context

StackExchange Code Review Q#90882, answer score: 5

Revisions (0)

No revisions yet.