Hui Wen Hui Wen - 2 years ago 78
HTML Question

JavaScript match selected text with div id

I am trying to show and hide certain div based on selected text in drop down list. The option in drop-down list is generated by getting id from certain class name. I thought of using looping of an array in javascript but am unsure how to do so. Sorry that i may sound unclear of what i wanted to do as i am lost and unsure how to do them.

My Codes:


var elements = document.body.getElementsByClassName("headline-bar");

window.onload = function() {

var year = document.getElementById("year");
for (i=0;i<elements.length;i++)
var Entry = document.createElement("option");
Entry.text = elements[i].textContent;
year.add(Entry ,null);


<select id="year">
<input type="submit" value="Submit">

<form action="#" id="release_year" method="post" >

<div class="release_holder" id="2015" style="margin-bottom: 20px">
<div class="headline-bar">2015</div>
<div class="content">hello there</div>

<div class="release_holder" id="2014" style="margin-bottom: 20px">
<div class="headline-bar">2014</div>
<div class="content">hello there</div>


JavaScript Loop array that i thought of using:

var selectedText = yearSelect.options[yearSelect.selectedIndex].text;
var classList = document.getElementByClassName('press_release_holder').id.split(/\s+/);
for (var i = 0; i < classList.length; i++) {
if (classList[i] === 'selectedText') {
//do something

Answer Source

Do the values of the dropdown list correspond to the year? i.e. the id of the div tag you want to hide.

If so, you can try the following:

var optionList = document.getElementById("year");
var selectedText = optionList.options[optionList .selectedIndex].value;

//hide the div with the id = selectedText
document.getElementById(selectedText).style.display = 'none';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download