0

I am creating HTML select dropdown (font-size). When I am selecting the value from the dropdown for example h1.

Under the dropdown I have the text which i need to apply h1.

I was trying to creating css class for all the heading tag from H1 - h6 and in the onClick of every option apply css using add and remove.

<select>
    <option>h1</option>
    <option>h2</option>
    <option>h3</option>
</select>
<div id="text">
    Text
</div>

But I don't now how to do that. Link

Kindly help me how to

2
  • are you using any libraries ( e.g. jquery? ) or you want it in pure javascript? Commented Apr 20, 2015 at 21:07
  • actually I was tyring in pure javascript Commented Apr 20, 2015 at 21:08

2 Answers 2

6

You need to listen onchange event on select element, and based on the selected value apply corresponding class to the div.

One possible implementation:

// Get select element
var select = document.querySelector('select');

// Bind onchange event
select.onchange = function() {
    document.querySelector('#text').className = this.value;
};

// Trigger event to apply initial value
select.onchange();
.h1 {font-size: 32px;}
.h2 {font-size: 24px;}
.h3 {font-size: 19px;}
<select>
    <option value="h1">h1</option>
    <option value="h2">h2</option>
    <option value="h3">h3</option>
</select>

<div id="text">Text</div>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much but is that possible in pure javscaript I guess this was Jquery right
0

You should use the addEventListener method instead of the onchange property because it is considered more flexible and is part of the DOM Events specification. So, this can be considered better practice. Using properties like onchange restricts you by only allowing you to assign one event handler at a time for the target element.

Below is a solution using JavaScript to add the change event listener to the element versus modifying the property of the element itself.

(function changeListener() {
  var select = document.querySelector('select'),
      text = document.getElementById('text');

  // add change listener
  select.addEventListener('change', function () {
    text.className = this.value;
  });

  // default size
  text.className = select.value;
}());
.h1 { font-size: 32px; }
.h2 { font-size: 24px; }
.h3 { font-size: 19px; }
<select>
    <option>h1</option>
    <option>h2</option>
    <option>h3</option>
</select>
<div id="text">
    Text
</div>

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.