Reputation: 29
HTML
JavaScript I have so Far
var $= function(selector){
var elements = [];
if (selector == "#some_id"){
elements.push( document.getElementById("some_id"));
}else if (selector == '.some_class'){
elements= document.getElementsByClassName("some_class");
} else if (selector == "div"){
elements = document.getElementsByTagName("div");
}else if (selector == "img"){
elements.push(document.getElementsByTagName("img"));
}
console.log(elements);
return elements;
};
Having a problem getting nested selectors like : ("img.some_class") and ("div.some_class#some_id")
Upvotes: 1
Views: 548
Reputation: 7
I suppose you were asked not to use neither JQuery nor querySelector()/ querySelectorAll(), like me.
You can find the nested selectors like this:
...} else if (selector == "div#some_id.some_class") {
elements.push(document.getElementById("some_id"));
} else if (selector == "div.some_class#some_id") {
elements.push(document.getElementById("some_id"));
}
...
Your answer is kind of great, because I spent two days trying to get it and yours is just so simple, I could complete the last two tests really quickly.
I still have no clue why this even works in the first place, and it's so NOT dry, but I guess it'll be useful for people in the future.
Upvotes: 0
Reputation: 4025
Have you tried querySelector
or querySelectorAll
?
Here are two simple examples:
var el = document.querySelector(".myclass");
var matches = document.querySelectorAll("div.note, div.alert");
See here for more information: https://developer.mozilla.org/en-US/docs/Web/API/document.querySelectorAll
A very simple simulation of jQuery selector:
$ = function (selector) {
return document.querySelectorAll(selector);
}
Upvotes: 2