Home > other >  Applying style to all elements with a name is failing
Applying style to all elements with a name is failing

Time:12-13

I am trying to apply styles to all elements with name "Phone". Applying individually works fine.

var input = document.getElementsByName("Phone")[0];
input.style.border = '1px solid #1D0F9D';
input.style.borderRadius = '18px';
input.style.width = '100%';
input.style.height = '30px';
input.style.paddingLeft = '50px';
input.style.paddingTop = '18px';
input.style.paddingBottom = '18px';
input.style.color = '#1D0F9D';
input.style.fontSize = '14px';
input.style.color = 'black';
input.style.outline = '0px solid #26B6D4';

This renders the input correctly: 1. Flag drop down 2. input field enter image description here

But looping over all the elements does not render the flag drop down: Similarly setting styles for class phone fails to render it correctly

var inputs = document.getElementsByName("Phone");
for (var i = 0; i < inputs.length; i  ) {
    inputs[i].style.border = '1px solid #1D0F9D';
    inputs[i].style.borderRadius = '18px';
    inputs[i].style.width = '100%';
    inputs[i].style.height = '30px';
    inputs[i].style.paddingLeft = '50px';
    inputs[i].style.paddingTop = '18px';
    inputs[i].style.paddingBottom = '18px';
    inputs[i].style.color = '#1D0F9D';
    inputs[i].style.fontSize = '14px';
    inputs[i].style.color = 'black';
    inputs[i].style.outline = '0px solid #26B6D4';
}

enter image description here

Code here : https://jsfiddle.net/hzorum8x/

Probably missing something very basic. what is it?

CodePudding user response:

As far as I am aware, you don't even need javascript in your case.

You've got on the <input>, so you can use the class you defined in the <style> section, instead of trying to target the name attribute. Your code should look something like this:

<style>
    .iti {
        width: 100%;
    }
    .phone {
      border: 1px solid #1D0F9D;
      border-radius: 18px;
      width: 100%;
      height: 30px;
      padding-left: 50px;
      padding-top: 18px;
      padding-bottom: 18px;
      color: #1D0F9D;
      font-size: 14px;
    }
</style>

I've also noticed that you defined color twice, and gave a 0px solid #26B6D4 outline, which will essentially not display, so I removed these two lines.

CodePudding user response:

If you only aim to change the style of the elements, using CSS would be simpler

However, the following sample code will hopefully help you

<input name="phone" />
<input name="phone" />
<script>
  addEventListener('load', () => {
    var elements = document.getElementsByName('phone');
    for (var i = 0; i < elements.length; i  ) {
        elements[i].style.backgroundColor = '#abcdef';
    }
  });
</script>
  • Related