user2059040
user2059040

Reputation: 13

using buttons for changing font size for the whole website using javascript

i am trying to implement accessibility tools and i have managed to change the font size of a paragraph once the button has been clicked but i tried altering the code so that it will work on all the paragraph and it does not work

<script>

function myFunction()

{
 var p =document.getElementsByTagName('p'); // Find the element
p.style.fontSize="1.5em";          // Change the style
}
</script>

<button type="button" style="background: #ccc url(images/small.jpg);  padding: 0.3em 1em"   onclick="myFunction()"></button>

this is how it worked before for just one paragraph but i am trying to more than one:

<script>
function myFunction()
{
x=document.getElementById("demo") // Find the element
x.style.fontSize="3.0em";          // Change the style
}
</script>

Upvotes: 1

Views: 2184

Answers (2)

jwl
jwl

Reputation: 10514

Your issue in the first code block is that getElementsByTagName returns an nodeList of elements (which you can pretend is an array). So you would need to do this:

var p =document.getElementsByTagName('p'); // Find the element
for(var i=0; i<p.length; i++) {
  p[i].style.fontSize="1.5em";          // Change the style
  }

However, a better approach would be to define some css classes to do this job for you.

<style>
body { /*normal size*/
  font-size: 1em;
}

body.largeFont {
  font-size: 1.5em;
}
</style>

<script>
function largeFont() {
  document.body.className="largeFont";
}
</script>

Upvotes: 2

freejosh
freejosh

Reputation: 11383

getElementsByTagName returns a NodeList, which is like an array, so you have to loop through them and apply the style to each element:

function myFunction() {
    var arr = document.getElementsByTagName('p');
    for (var i = 0; i < arr.length; i++) {
        arr[i].style.fontSize = "1.5em";
    }
}

Upvotes: 3

Related Questions