jQuery HTML | CSSを操作する
本日は、jQuery で HTML | CSSを操作する命令をまとめたいと思います。
【使用する理由】
アニメーションなど、あるタイミングで画面を動かしたい時等、もともと書いてあるスタイルシート側の命令を書き換える際に使用します。
【基本】
<script>
$(function(){
$('※※').命令内容('○○○○');
});
</script>
- セレクター=※※部分
HTML | CSSを操作する命令
【挿入】
- HTMLの要素内の先頭に挿入
$('※※').prepend('変更後');
→pre は前にの意味append()before()after()
- HTMLの要素内の最後に挿入
$('※※').append('変更後');
<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>無題ドキュメント</title>
<script src="jquery-1.11.0.min.js"></script>
<script>
$(function(){
$('p#first').prepend('<strong>行頭に挿入</strong>');
$('p#first').append('<strong>行末に挿入</strong>');
});
</script>
</head>
<body>
<p id="first">テキストテキスト</p>
</body>
</html>
- HTMLの要素内の前に挿入
$('※※').before('挿入したい内容');
<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>無題ドキュメント</title>
<script src="jquery-1.11.0.min.js"></script>
</script>
<script>
$(function(){
$('p#first').before('<h1>前に挿入</h1>')
});
</script>
</head>
<body>
<p id="first">テキストテキスト</p>
</body>
</html>
- HTMLの要素内の後ろに挿入
$('※※').after('挿入したい内容');
<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>無題ドキュメント</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script>
$(function(){
$('p#first').after("<h1>後ろに挿入</h1>");
});
</script>
</head>
<body>
<p id="first">テキストテキスト</p>
</body>
</html>
【移動】
- HTMLの要素内の先頭に移動
$('※※').prependTo('p');
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>無題ドキュメント</title>
<script src="jquery-1.11.0.min"></script>
<script>
$(function(){
$("strong").prependTo("p");
});
</script>
</head>
<body>
<p id="first">テキストテキスト</p>
<strong>先頭に移動</strong>
</body>
</html>
- HTMLの要素内の最後に移動
$('※※').appendTo('p');
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>無題ドキュメント</title>
<script src="jquery-1.11.0.min"></script>
<script>
$(function(){
$("strong").appendTo('p');
});
</script>
</head>
<body>
<p>テキストテキスト</p>
<strong>最後に移動</strong>
</body>
</html>