Reputation: 55
I want to add attribute class='notranslate'
in <pre>
to prevent Google Translating content in <pre>
tag.
I use this JavaScript, and it work.
<script type='text/javascript'>
//<![CDATA[
var pre = document.getElementsByTagName("PRE")[0];
var att = document.createAttribute("class");
att.value = "notranslate";
pre.setAttributeNode(att);
//]]>
</script>
But there is problem. That's JavaScript only work at first <pre>
tag.
Anyone can help me, how to Add class='notranslate'
in entire tag <pre>
?
Thank you and sorry for my english.
Upvotes: 0
Views: 78
Reputation: 9368
You are selecting only the first element by adding [0]
. You need to iterate over the entire NodeList
You can also use the classList.add
to prevent clobbering of existing classes
Object.values(document.getElementsByTagName('pre'))
.forEach(pre => pre.classList.add('notranslate'))
Upvotes: 0
Reputation: 111
It only works at the first pre tag because you are selecting the first element of the returned array.
Try
for (let pre of document.getElementsByTagName('pre')) {
// ... your manipulation code
}
Upvotes: 0
Reputation: 12152
Use forEach to iterate over the values of the object which is returned by the getElementsByTagName and create and append attributes in the loop
var pre = document.getElementsByTagName("PRE");
Object.values(pre).forEach((x)=>{
var att = document.createAttribute("class");
att.value = "notranslate";
x.setAttributeNode(att);
})
<pre>a</pre><pre>b</pre><pre>c</pre>
Upvotes: 0
Reputation: 18240
Dont do document.getElementsByTagName("PRE")[0];
which gives you the first element (thats what the[0]
is for) but use a loop.
document.getElementsByTagName("PRE").forEach(pre => {
const att = document.createAttribute("class");
att.value = "notranslate";
pre.setAttributeNode(att);
});
Upvotes: 1