最速怪談選手権

JavaScriptで MDNのクリップボードとのやりとりをしています。

クリップボードとのやりとり
https://developer.mozilla.org/ja/docs/Mozilla/Ad …

このページのソースを変更しようと思っています。
jQeryならうまくいきます。

## html
<input id="input" type="text"/>
<button id="copy">Copy</button>

## jQery
function copy() {
var copyText = document.querySelector("#input");
copyText.select();
document.execCommand("copy");
}

document.querySelector("#copy").addEventListener("click", copy);

を JavaScript に 変更しようと

## JavaScript
function copy() {
var input2 = document.getElementById("input");
var copyText = document.querySelector(input2);
copyText.select();
document.execCommand("copy");
}

var copy2 = document.getElementById("button");
document.querySelector(copy2).addEventListener("click", copy);

としています。
しかし、 うまくいきません。
エラーがでます

## エラー
Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '[object HTMLButtonElement]' is not a valid selector.

どうすればよいのでしょうか?

A 回答 (1件)

こんばんは



>.querySelector(input2);
querySelector()の引数は、文字通りセレクタ(文字列)です。
そのあたりを何か勘違いしていませんか?
https://developer.mozilla.org/ja/docs/Web/API/Do …

一方で、
>## jQery
として挙げているスクリプトは、別にjQuery環境下でなくとも動作するものと思いますけれど、どこを変えたいのでしょうか。
    • good
    • 0
この回答へのお礼

回答ありがとうございました。

あ~ そうでしたそうでした。
#input とか .input と書くのがあったのを思い出しました。

これでもうまくいきました。


## JavaScript

function copy() {
var copyText = document.getElementById("input");
copyText.select();
document.execCommand("copy");
}
document.getElementById("button").addEventListener("click", copy);

お礼日時:2019/02/13 00:08

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!