0

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.

2
  • var pre is a list of nodes. Loop through them and set your attribute to all if them. Commented Feb 7, 2019 at 6:07
  • Using jQuery: $('pre').addClass("notranslate"); Commented Feb 7, 2019 at 6:08

4 Answers 4

1

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);
});
Sign up to request clarification or add additional context in comments.

Comments

0

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>

1 Comment

Wow, Thank you for solution.
0

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
}

Comments

0

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'))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.