目次
var idElem = document.getElementById("id");
var classElem = document.getElementsByClassName("class");
var tagElem = document.getElementsByTagName('p');
var query = document.querySelector("div span");
var query = document.querySelectorAll("div span");
document.getElementById("id").parentNode;
document.getElementById("id").children;
document.getElementById("id").firstElementChild;
document.getElementById("id").lastElementChild;
document.getElementById("id").previousElementSibling;
document.getElementById("id").nextElementSibling;
const el = document.getElementById("id"); // class名「item」が存在すればtrue if(!!el.querySelector(".item")){ alert("true"); }else{ alert("false"); }
let tag = document.querySelector("a"). innerHTML;
// aタグのリンク先を取得 let link = document.querySelector("a").getAttribute('href');
let text = document.querySelector("p").textContent;
const el = document.getElementById("id"); let el_display = getComputedStyle(el)["display"];
const el = document.getElementById("id"); let el_w = parseFloat(getComputedStyle(el, null).width.replace("px", ""))
const el = document.getElementById("id"); let el_H = parseFloat(getComputedStyle(el, null).height.replace("px", ""))
const el = document.getElementById("id"); var rect = el.getBoundingClientRect(); console.log("要素x座標:" + rect.x); console.log("要素y座標:" + rect.y); console.log("要素横幅:" + rect.width); console.log("要素高さ:" + rect.height); console.log("ドキュメント先頭から要素までの縦スクロール値:" + rect.top); console.log("ドキュメント左端から要素までの幅:" + rect.left); console.log("ドキュメント終点から要素までの縦スクロール値:" + rect.bottom);
const el = document.getElementById("id"); let el_inW = el.offsetWidth;
const el = document.getElementById("id"); function outerWidth(el) { var width = el.offsetWidth; var style = getComputedStyle(el); width += parseInt(style.marginLeft) + parseInt(style.marginRight); return width; } let el_outW = outerWidth(el);
const el = document.getElementById("id"); let el_inH = el.offsetHeight
const el = document.getElementById("id"); function outerHeight(el) { var height = el.offsetHeight; var style = getComputedStyle(el); height += parseInt(style.marginTop) + parseInt(style.marginBottom); return height; } let el_outH = outerHeight(el);
const el = document.getElementById("id"); let offsetT = el. offsetTop; let offsetL = el.offsetLeft;
var div = document.createElement('div'); div.textContent = 'hoge';
document.getElementById("id").appendChild(div);
const $main = document.getElementById("id"); $main.insertBefore(div, $main.firstChild);
const $main = document.getElementById("id"); $main.parentNode.insertBefore(div, element.nextSibling);
// 指定classのみを追加 document.getElementById("main").classList.add("add-class"); // 複数classを追加 document.getElementById("main").classList.add('make', 'me', 'look', 'rad');
// 指定classのみを削除 document.getElementById("main").classList.remove("remove-class"); // 複数classを削除 document.getElementById("main").classList.remove('cool', 'make', 'me');
const $main = document.getElementById("main"); $main.classList.toggle("toggle-class"); // clickイベントの場合 $main.addEventListener('click', () => { $main.classList.toggle('toggle-class'); });
const $main = document.getElementById("main"); // "active"クラスを持っていればtrueが返る var a = $main.classList.contains("active"); console.log(a); // true // "active"クラスを持っていたら削除・持っていなかったら追加 if ($main.classList.contains('active')) { $main.classList.remove('active'); } else { $main.classList.add('active'); }
document.getElementById("id").cloneNode(true);
const el = document.getElementById("id"); const child = document.getElementById("child"); if(el !== child && el.contains(child);){ alert("true"); }else{ alert("false"); }
var elements = document.querySelectorAll(".item"); Array.prototype.forEach.call(elements, function(el, i){ alert(i); });
while(el.firstChild) el.removeChild(el.firstChild);
// 指定要素内の子要素数を表示 function filterFunc(index){ var child = index.children; console.log(child.length) } Array.prototype.filter.call(document.querySelectorAll(".item"), filterFunc);
const el = document.getElementById("id"); function index(el) { if (!el) return -1; var i = 0; do { i++; } while (el = el.previousElementSibling); return i; }
el === otherEl;
var textbox = document.getElementById('main').value;
var radio = document.getElementById("main"); if(radio.checked){ console.log("チェックされている"); } else { console.log("チェックされていない"); }
var formElem = document.getElementById("form") ; var radioList = formElem.radio; var val = radioNodeList.value; if (val === "") { console.log("未選択"); } else { console.log(val); }
const selectElement = document.querySelector('.form-select'); selectElement.addEventListener('change', (event) => { console.log(event.target.value); });
const input = document.querySelector('input'); input.addEventListener('change', updateValue); function updateValue(e) { console.log(e.srcElement.value); }
// 要素#mainの文字色を#fffに変更 document.getElementById("main").style.color = "#fff"; // プロパティに"-"が含まれる場合(background-color) document.getElementById("main").style.backgroundColor = "#fff"; // 一括でstyle指定したい場合 document.getElementById("main").setAttribute("style","position:absolute; bottom:0, left:0; z-index:1;"); // 複数の要素に共通style指定したい場合 const cssString = "font-size:18px; background-color:red"; document.getElementById("elemA").setAttribute("style",cssString); document.getElementById("elemB").setAttribute("style",cssString); // 既存要素のスタイル状態を取得 var thisStyle = document.defaultView.getComputedStyle(document.getElementById("main"), null).color;
// 画像要素#thumbのsrc属性を取得 document.getElementById("thumb").getAttribute("src"); // 画像要素#thumbのsrc属性を「/thumb.png」に変更 document.getElementById("thumb").setAttribute("src", "/thumb.png")
el.style.display = 'none';
el.style.display = '';
const btn = document.querySelector('.btn'); btn.addEventListener('mouseenter', (e) => { console.log('マウスオーバー'); }); btn.addEventListener('mouseleave', (e) => { console.log('マウスアウト'); });
// 対象がIDを持っている場合 document.addEventListener("click", function(event) { if(event.target.id === "button") { alert("クリックされました"); } }, false); // 対象がclassを持っている場合 document.addEventListener("click", function(event) { if(event.target.classList.contains("button")) { alert("クリックされました"); } }, false);
var xhr = new XMLHttpRequest(); xhr.open('POST', 'https://httpbin.org/post'); xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded;charset=UTF-8'); xhr.send('data=yanyo&since=2012');
var request = new XMLHttpRequest(); request.open('GET', '/my/url', true); request.onload = function() { if (this.status >= 200 && this.status < 400) { // JSONデータ取得成功 var data = JSON.parse(this.response); } else { // JSONデータ取得失敗 } }; request.onerror = function() { // 接続エラー }; request.send();
var request = new XMLHttpRequest(); request.open('POST', '/my/url', true); request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); request.send(data);
var request = new XMLHttpRequest(); request.open('GET', '/my/url', true); request.onload = function() { if (this.status >= 200 && this.status < 400) { // 成功時の処理 var resp = this.response; } else { // 失敗時の処理 } }; request.onerror = function() { // 接続エラー }; request.send();
// 2秒間で上100px、左100px移動 document.getElementById("main").animate([ { 'top' : '100px' }, { 'left' : '100px' } ], 2000); // 5秒間で2フレームに分けてフェードイン document.getElementById("main").animate([ { opacity: 0, color: "#fff"}, { opacity: 1, color: "#000"} ], 5000);
el.classList.add('show'); el.classList.remove('hide');
.show { transition: opacity 400ms; } .hide { opacity: 0; }
el.classList.add('hide'); el.classList.remove('show');
.show { opacity: 1; } .hide { opacity: 0; transition: opacity 400ms; }
let array = [1, 2, 3]; array.forEach(function(item, i){ console.log(item + 1); });
let array = ['A', 'B', 'C']; let array = array.map(function(value, index){ return value + 'だよ'; }); console.log(array) --> ['Aだよ', 'Bだよ', 'Cだよ'];
var extend = function(out) { out = out || {}; for (var i = 1; i < arguments.length; i++) { if (!arguments[i]) continue; for (var key in arguments[i]) { if (arguments[i].hasOwnProperty(key)) out[key] = arguments[i][key]; } } return out; }; extend({}, objA, objB);
let array = ["A","B","C"]; console.log(array.indexOf("C")); --> 2 console.log(array.indexOf("D")); --> -1