0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

4/5 jsコードレシピ集 学習 classList.add textContent innerHTML

Last updated at Posted at 2019-04-04

要素にクラスを追加
要素.classList.add(追加したいクラス)

要素のテキストを取得
要素.textContent

要素のテキストをXXXXXで書き換え
要素.textContent = "XXXXX"

要素のHTMLをYYYYYで書き換え
innerHTML = "YYYYY"

textContentはテキストのみ取得するが、innerHTMLはHTMLを取得出来るので、cssの操作も可能。

js
// weather要素を取得
const weatherElement = document.getElementById('weather');

// クリックしたらイベント発火
weatherElement.addEventListener('click', () =>
{
  // weather要素にnew-classというクラスを追加
  weatherElement.classList.add('new-class');
  
  // weather要素のテキストを書き換える
  weatherElement.textContent = "気温は<strong>66℃</strong>になる予定です"

  // アラートでweather要素のテキストを表示
  alert(weatherElement.textContent);
  // #出力結果 = 気温は<strong>66℃</strong>になる予定です

  // weather要素のHTMLを書き換え、テキストを太字にするstrongタグを追加する
  weatherElement.innerHTML = "気温は<strong>66℃</strong>になる予定です";
// #出力結果(太字、背景が黄緑) = 気温は66℃になる予定です
});
html
<p id="weather>今日は猛暑です<p>
css
.new-class {
  background-color: greenyellow;
}
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?