使用するための準備
bodyタグ内に下記を設置
ここからJQueryのリンクCDNを取得して、使用できるようにする。
// jqueryを使えるように取得
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function() {
// 実施したい処理
});
</script>
セレクタの指定方法
基本的な指定方法
// 要素の指定
$('a')
// idの指定
$('#id')
// classの指定
$('.class')
// 子要素の指定
$('#id > .class')
// 配下の全ての指定
$('#id .class')
// and条件
$('#id, .class')
// 隣の要素を指定
$('#id + .class')
フィルタを使用した指定方法
// indexは0からスタート
// index2のli要素を選択
$('#id > li:eq(2)')
// index2より大きいli要素を選択(greater thanの略)
$('#id > li:gt(2)')
// index2より小さいli要素を選択(less thanの略)
$('#id > li:lt(2)')
// indexが偶数のli要素を選択
$('#id > li:even')
// indexが奇数のli要素を選択
$('#id > li:odd')
// テキストに2が含まれているli要素を選択
$('#id > li:contains(2))')
// 最初のli要素を選択
$('#id > li:first')
// 最後のli要素を選択
$('#id > li:last')
メソッドを使用した指定方法
// 親要素を指定
$('#id').parent()
// 子要素を指定
$('#id').children()
// 次の要素を指定
$('#id').next()
// 前の要素を指定
$('#id').prev()
// 兄弟ノード全てを選択(自身は含まない)
$('#id').siblings()
セレクタメソッドを使用した指定方法
// 属性が一致する要素を取得
$('a[href="http://google.com"]')
// 属性が一致しない要素を取得
('a[href!="http://google.com"]')
// 属性に一部含まれている要素を取得
$('a[href*="google"]')
// 属性の冒頭が一致した要素を取得
$('a[href$="https://"]')
// 属性の末尾が一致した要素を取得
$('a[href$=".jp"]')
その他の指定方法
// a要素 且つ 属性が一致する要素を取得
($('a').attr('href', 'http://google.co.jp')
タグ操作
要素の追加/変更/作成
const 変数 =
を外すと要素の変更になる
// 要素の作成(div要素の中にdivを追加)
const div = $('<div>').append($('<div>'));
// idを追加する
const div = $('<div>').attr('id', 'id名');
// classを追加する
const div = $('<div>').attr('class', 'class名');
const div = $('<div>').addClass('class名');
// htmlの追加
const div = $('<div>').html('追加したいHTML');
// textの追加
const div = $('<div>').text('追加したいテキスト');
// valueの追加
const div = $('<div>').val('追加したいvalue');
// プロパティの追加
const div = $('<option>').prop('selected', true);
const div = $('<input>').attr('type', 'checkbox').prop('checked', true);
// 下記は変更のみ
// 内容を削除
$('#id').empty();
// 要素自体を削除
$('#id').remove();
要素の追加
// 要素を作成
const div = $('<div>').text('text');
// li要素index2の前に追加
$('#id > li:eq(2)').before(div);
li.insertBefore($('#id > li:eq(2)'));
// li要素index2の後ろに追加
$('#id > li:eq(2)').after(div);
li.insertAfter($('#id > li:eq(2)'));
// 子要素の先頭に追加(複数ある場合は全てに追加される)
$('.class > li:eq(2)').after(div);
// 子要素の末尾に追加(複数ある場合は全てに追加される)
$('.class > li:eq(2)').append(div);
イベント操作
// クリックイベント
$('#id').click(() => alert('hi!'));
// 続けて書くことで複数イベントの設定が可能
// アロー関数を使用する場合
$('#box')
.mouseover(e => {
$(e.target).css('background', 'green');
})
.mouseout(e => {
$(e.target).css('background', 'red');
})
.mousemove(e => {
$(e.target).text(e.pageX);
});
// functionを使用する場合
$('#box')
.mouseover(function() {
$(this).css('background', 'green');
})
.mouseout(function() {
$(this).css('background', 'red');
})
.mousemove(function(e) {
$(this).text(e.pageX);
});
イベントの種類はこちらを参照
fetch APIの使用方法
まず、JQueryが組み込まれているかをデベロッパーツールのConsoleで確かめます。
バージョン情報がでてきたらそのドメインはJQueryでのfetchが可能です。
バージョンの確認
$.fn.jquery
url = '';
fetch(url)
.then(res => res.text())
.then(txt => {
console.log(txt);
console.log($('.class', txt).text());
});