javascript タイトルを取得または変更する
- 2020.10.12
- javascript
- javascript

javascriptで、document.titleを使用して、タイトルを取得または変更するサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ firefox 80
document.title使い方
document.titleを使用すると、サイトのタイトルを取得することが可能です。
1 |
var titlename = document.title; |
document.title使い方
1 2 3 4 |
var titlename = document.title; console.log(titlename); // サイトのタイトル document.title = "サイトタイトル" // サイトのタイトルが変更される |
サンプルコード
以下は、
「タイトル取得」ボタンで、サイトのタイトルを取得して
「タイトル変更」ボタンで、サイトのタイトルを変更する
サンプルコードとなります。
※cssには「bootstrap material」を使用してます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>mebeeサンプル</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons"> <link rel="stylesheet" href="https://unpkg.com/bootstrap-material-design@4.1.1/dist/css/bootstrap-material-design.min.css" integrity="sha384-wXznGJNEXNG1NFsbm0ugrLFMQPWswR3lds2VeinahP8N0zJw9VWSopbjv2x7WCvX" crossorigin="anonymous"> </head> <style> .main { margin: 0 auto; margin-top: 200px; display: flex; flex-direction: column; align-items: center; font-size: 25px; } </style> <script> function hoge() { // サイトのタイトルを取得 var result = document.title; document.getElementsByClassName('badge')[0].textContent = result; }; function foo() { // サイトのタイトルを変更 document.title = "javascriptサンプル"; document.getElementsByClassName('badge')[0].textContent = document.title; }; </script> <body> <div class="main"> <h5><span class="badge badge-secondary">サイトタイトルを表示</span></h5> <button type="button" class="btn btn-raised btn-primary" onclick="hoge()">タイトル取得</button> <button type="button" class="btn btn-raised btn-secondary" onclick="foo()">タイトル変更</button> </div> </body> </html> |
サイトのタイトルが変更されていることが確認できます。

-
前の記事
javascript 左側のみか右側のみにある空白を全て削除する 2020.10.12
-
次の記事
javascript エラー「Uncaught TypeError: Cannot set property name of #object which has only a getter」が発生する原因と対処法 2020.10.12
コメントを書く