Home > Back-end >  How do I make it so that when you click an elment that the code tag, you copy its innerHTML
How do I make it so that when you click an elment that the code tag, you copy its innerHTML

Time:07-16

I want to make it so that when any element with the code tag gets clicked, the user copies the element's innerHTML. But the thing is I have 6-7 elements with the code tag, I've tried this:

const code1 = document.getElementsByTagName('CODE')[0];
const code2 = document.getElementsByTagName('CODE')[1];
const code3 = document.getElementsByTagName('CODE')[2];
const code4 = document.getElementsByTagName('CODE')[3];
const code5 = document.getElementsByTagName('CODE')[4];
const code6 = document.getElementsByTagName('CODE')[6];
const code7 = document.getElementsByTagName('CODE')[7];

function copytext(text) {
    navigator.clipboard
        .writeText(text)
        .then(() => {
        })
        .catch(() => {
            alert("something went wrong");
        });
}

code1.addEventListener('click', function handleClick() {
    copytext(hello1);
});

code2.addEventListener('click', function handleClick() {
    copytext(hello2);
});

code3.addEventListener('click', function handleClick() {
    copytext(hello3);
});

code4.addEventListener('click', function handleClick() {
    copytext(hello3);
});

code5.addEventListener('click', function handleClick() {
    copytext(hello4);
});

code6.addEventListener('click', function handleClick() {
    copytext(hello5);
});

code7.addEventListener('click', function handleClick() {
    copytext(hello6);
});

But I feel like it's way too repetitive. Is there a way to select every element with a code tag, and copy its innerHTML without having to write a function for each and every one?

CodePudding user response:

You access the this element

for(let element of document.getElementsByTagName('CODE')){
  element.addEventListener('click',GetInnerHTML);
}
function GetInnerHTML(){console.log(this.innerHTML);}
CODE{display:block}
<CODE>A</CODE>
<CODE>B</CODE>

CodePudding user response:

The document.getElementsByTagName() to returns an array so you can just do

let codes = document.getElementsByTagName();
codes.foreach((element)=>{
element.addEventListener('click', () => {copytext(element)})
});
  • Related