2017-02-20 5 views
0

IDまたはクラスを持たない入力タグのIDを追加するにはどうすればよいですか?このようなことが可能です:JavaScriptで入力タグのIDを追加するにはどうすればよいですか?

<div id="1">hey all</div> 
<input type="text" name="txt" /> 

<script> 
    document.querySelector('input[type="search"]').id = 'sinput'; 
    document.getElementById("sinput").addEventListener("keypress", function() { 
     document.getElementById("1").style.display ="none"; 
    }); 
</script> 
+1

'' – nogad

+3

あなたの入力タイプは 'text'ですが、セレクタに取得しようとしています'search' ... – NewToJS

答えて

0

次のことを試してみてください。

var elem = document.getElementsByTagName('input'); 
 
elem[0].setAttribute("id", "txtName"); // important to use proper index here in case there are multiple input elements in the document. 
 
console.log(document.getElementsByTagName('input')[0])
<input type="text" name="txt" />

0

わかりました、私はあなたの現在のソースコードとそれに問題があることを伝える答えを見ていませんあなたが私のコメントを認めているようには見えないので、あなたは働くスニペットが行うことをあなたに示しているかもしれません。

を変更する必要がある唯一のものは、あなたのセレクタ'input[type="search"]'に一致するか、入力タイプ'input[type="text"]'に一致するように、あなたのセレクタを変更するにはtextからsearchtype属性です。

変更入力type = 検索

document.querySelector('input[type="search"]').id = 'sinput'; 
 
document.getElementById("sinput").addEventListener("keypress", function() { 
 
     document.getElementById("1").style.display ="none"; 
 
});
<div id="1">hey all</div> 
 
<input type="search" name="txt" />


または変更セレクタinput[type="TEXご質問があれば、T"]

document.querySelector('input[type="text"]').id = 'sinput'; 
 
document.getElementById("sinput").addEventListener("keypress", function() { 
 
     document.getElementById("1").style.display ="none"; 
 
});
<div id="1">hey all</div> 
 
<input type="text" name="txt" />

は、下記のコメントして自由に感じると私はできるだけ早くあなたに戻って取得します。

こちらがお役に立てば幸いです。ハッピーコーディング!

+0

ありがとうございました。 それがこのプロジェクト 「私は入力をEnterキーを押したときに、すべてのテーブルを表示したい」 このウェブサイトのプロジェクト http://sci.mu.edu.iq/?page_id=のための新しいプロジェクト で私と一緒に仕事だではなく、 3347の plsはコードのために私に –

+0

これを助ける

関連する問題