JavaScript
jQuery

jQueryを使わずjavascriptだけで書き直した際の記法メモ

More than 3 years have passed since last update.

パフォーマンスが重要な部分では、やっぱりjQueryは気になる。。。
検索するとなにやらVanilla jsというのが盛り上がっていた。

ってもこれただのjQuery使わず、javascript使おうぜって話なだけだけどwww
という事で今のjQueryのメソッドをすべてjsで置き換えたらどうなんだ?と思い対応表をまとめました。

jQuery ⇔ vanilla(普通のjavascript)

参考:
YOU MIGHT NOT NEED JQUERY
Choosing Vanilla JavaScript

live(on) event

jQuery

$(document).on('click', '.hoge', function(){  
  // function
});

vanilla

document.addEventListener('click', function (e) {
  if (e.target.className ==='hoge') {
    // function
  } 
});

click event

jQuery

$('a').click(function(){
    // code here
});

vanilla

var anchors =document.getElementsByTagName("a");
for(var z =0; z < anchors.length; z++){
    var elem = anchors[z];   
    elem.onclick = function(){
        // code here
    };
}

------

var clickHandler = function() { 
  // Your click handler
};

var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
  var current = anchors[i];
  current.addEventListener('click', clickHandler, false);
}

find

jQuery

$(el).find(selector).length;

vanilla

el.querySelector(selector) !== null
el.querySelectorALL(selector) !== null // return HTMLCollection

attributes

jQuery

$('img').filter(':first').attr('alt', 'My image')

vanilla

document.querySelector('img').setAttribute('alt', 'My image')

.closest

jQuery

var test = $("#test");
var target = test.closest('div');

vanilla

var test = document.getElementById("test");
var target = Closest(test, "div");

var Closest = function(element, tagname) {
  tagname = tagname.toLowerCase();
  do {
    if(element.nodeName.toLowerCase() === tagname){
      return element;
    }   
  }while(element = element.parentNode)
  return null;
};

パフォーマンス比較

change

jQuery

 $('#Email').change(function() {
    $('#UserName').val($(this).val());
 });

vanilla

function addEventHandler(elem, eventType, handler) {
    if (elem.addEventListener)
        elem.addEventListener (eventType, handler, false);
    else if (elem.attachEvent)
        elem.attachEvent ('on' + eventType, handler); 
}

addEventHandler(document, 'DOMContentLoaded', function() {
    addEventHandler(document.getElementById('Email'), 'change', function() {
        document.getElementById('UserName').value = this.value;
    });
});

ajax

jQuery

$.ajax({
  method: "post",
  url : "http://localhost:3000/api/v1/accounts",
  data: {}
}).done(function(data ,status){
  //成功のアニメーション
}).fail(function(state){
  //失敗のアニメーション
}); 

vanilla

var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4 && xmlhttp.status != 200) {
    // What you want to do on failure
    alert(xmlhttp.status + " : " + xmlhttp.responseText);
  }
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    // What you want to do on success
    onSuccessLogin();
  }
}

xmlhttp.open("POST", "../REST/session.aspx?_method=put", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Cache-Control", "no-cache"); // For no cache
xmlhttp.send("data=" + JSON.stringify(dataObject, null,4));

==========<<番外編>>==========

var data = {
  user_id: 1,
  text: "hash形式で生成したデータ送りたい"
}

xmlhttp.send(EncodeHTMLForm(data));

function EncodeHTMLForm(data){
  var params = [];
  for(var name in data){
    var value = data[name];
    var param = encodeURIComponent(name).replace(/%20/g, '+')
      + '=' + encodeURIComponent(value).replace(/%20/g, '+');
    params.push(param);
  }
  return params.join('&');
}