Ching Ching
Ching Ching

Reputation: 1049

javascript find() function without jquery

I love to trying something new. So, I decided to make my own function without using jquery. I'm trying to build find()

So, this is my code :

function $(el) {
  var firstChar = el.charAt(0),
      id = document.getElementById(el.slice(1));

  switch (firstChar) {
    case "#":
      return id;
      break;
  }
}

function find(el, loop) {
  return getElementsByTagName(el)[loop];
}

$("#test").find("h1", 0).innerHTML = "some text";
<div id="test">
  <h1>test one</h1>
  <h2>test two</h2>
</div>

It's not working, in my dreamweaver error log, it said that getElementsByTagName is not defined.

What is wrong with my code?

Upvotes: 6

Views: 9139

Answers (1)

t.niese
t.niese

Reputation: 40862

getElementsByTagName has to be called on a DOMElement. e.g. document.getElementsByTagName or yourElement.getElementsByTagName.

An equivalent to find would be querySelectorAll and querySelector

 document.getElementById("#test").getElementsByTagName("h1")[0].innerHTML = "some text";

OR

 document.getElementById("#test").querySelector("h1").innerHTML = "some text";

OR

 document.getElementById("#test").querySelectorAll("h1")[0].innerHTML = "some text";

A simple implementation, similar to the way it is implemented in jQuery, but be award that is just a proof of concept code, nothing to be used in production code:

function $(selector) {

    function ResultSet(elements) {
        var i;

        //make ResultSet to an array like object
        this.length = elements.length;

        //copy the values from elements to this 
        for (i = 0; i < this.length; i++) {
            this[i] = elements[i];
        }

    }

    ResultSet.prototype.find = function (selector) {
        var completeList = [],
            result, i;

        //loop through each element
        for (i = 0; i < this.length; i++) {
            //find the find the matching elements using the stored element as base for the query
            result = this[i].querySelectorAll(selector);
            result = Array.prototype.slice.call(result); //convert NodeList to array
            completeList = completeList.concat(result); //concat the result
        };

        //return the collected elements as new result set
        return new ResultSet(completeList);
    };


    return new ResultSet( document.querySelectorAll(selector) );
}


$("#test").find("h1")[0].innerHTML = "some text";
<div id="test">
  <h1>test one</h1>
  <h2>test two</h2>
</div>

Upvotes: 11

Related Questions