▲TOPへ戻る

【javascript】属性を設定(setAttribute)、取得(getAttribute)、確認(hasAttribute)する

topBtn

setAttribute 設定

セレクトボックスのオプションに属性を設定します。

  //  設定  setAttribute(属性, 値)  
  lang.firstElementChild.setAttribute('selected', 'true')
  lang.firstElementChild.setAttribute('disabled', 'true')

  const langType = ['', 'html', 'css', 'javascript']
  for (let i = 0; i < lang.children.length; i++) {
    const element = lang.children[i];
    element.setAttribute('value', langType[i])
  }

属性が設定されました。

setAttribute

getAttribute 取得

  //  取得  getAttribute(属性)  
  console.log(lang.firstElementChild.getAttribute('selected'));
  console.log(lang.firstElementChild.getAttribute('disabled'));
  for (let i = 0; i < lang.children.length; i++) {
    const element = lang.children[i];
    console.log(element.getAttribute('value'));
  }

取得できました。

getAttribute

hasAttribute 確認

  //  確認  hasAttribute(属性)    返り値はtrue or false
  console.log(lang.firstElementChild.hasAttribute('selected'));
  console.log(lang.firstElementChild.hasAttribute('disabled'));
  console.log(lang.children[1].hasAttribute('disabled'));
  console.log(lang.children[1].hasAttribute('value')); 

存在すればtrue, なければfalseが返ってきます。

hasAttribute
point

追加・変更 setAttribute( '属性', '値' )

取得:getAttribute( '属性' )

確認 : hasAttribute('属性') 返り値はtrue or false

こんな記事も読まれています。

profile

パソコン好きなガオ

コロナ禍によるステイホームを機にプログラミングを学ぶ。パソコンに関してはプロではないが、ちょっと詳しい程度。

パソコン

javascript

カメラ

ブログ