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.

JQueryで指定したDOM要素の取得・書き換え

Posted at

この記事について

この記事ではセレクタで指定したDOM要素を以下のメソッドを使って操作する。

利用するメソッド

以下を利用する

text()
→指定したDOM要素のコンテンツを書き換える
html()
→指定したDOM要素のHTMLを変更する
val()
→VALUE属性を取得する
remove()
→指定したDOM要素を消す
empty()
→指定したDOM要素のコンテンツを消す

サンプルコード

上記のメソッドを使ってDOM要素を操作する

sample.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
  <title>sample</title>
</head>
<body>
  <a href="hogehoge.com" data-sitename="googleのサイト">googleリンク</a>
  <script>
    $(function(){
      $('a').text('hello!');
    });
  </script>
</body>
</html>
//googleリンクからhello!にテキストが変更される
sample.html
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
  <title>sample</title>
</head>
<body>
  <a href="hogehoge.com" data-sitename="googleのサイト">googleリンク</a>
  <script>
    $(function(){
      $('a').html('<h1>h1要素に変更<h1>');
    });
  </script>
</body>
</html>
//h1要素に変更される
sample.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
  <title>sample</title>
</head>
<body>
  <form method="post">
    <input type="text" value="hogehoge">
  </form>
  <script>
    $(function(){
      console.log($('input').val());
    });
  </script>
</body>
</html>
//input要素のvalueを取得して、コンソールで表示
sample.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
  <title>sample</title>
</head>
<body>
  <form method="post">
    <input type="text" value="hogehoge">
  </form>
  <script>
    $(function(){
      $('input').remove();
    })
  </script>
</body>
</html>
//input要素を消すので何も表示されない
sample.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
  <title>sample</title>
</head>
<body>
    <p>hogehoge</p>
  <script>
    $(function(){
      $('p').empty();
    })
  </script>
</body>
</html>

//p要素は消えていないが、hogehogeというテキストが消えている状態
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?