Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get inner html of the selected option

Tags:

javascript

dom

I have something like this:

select = document.getElementById("select");
select.onchange = function(){
  alert(this.value); //returns the selected value
  alert(this.innerHTML); //returns the entire select with all the options
  alert(this.selected.innerHTML); //this is what I want, but doesn't work, of course
};

How can I get the innerHTML of the selected option in pure js? (no frameworks).

like image 843
methodofaction Avatar asked Feb 21 '11 17:02

methodofaction


People also ask

How do I find the inner HTML of an element?

The Element property innerHTML gets or sets the HTML or XML markup contained within the element. To insert the HTML into the document rather than replace the contents of an element, use the method insertAdjacentHTML() .

What is the difference between innerText and innerHTML?

innerText returns all text contained by an element and all its child elements. innerHtml returns all text, including html tags, that is contained by an element.


4 Answers

Try:

alert(this.options[this.selectedIndex].text);

Demo:

<select onchange="alert(this.options[this.selectedIndex].text)">
  <option>foo
  <option>bar
  <option>foobar
</select>
like image 127
Dr.Molle Avatar answered Oct 01 '22 11:10

Dr.Molle


I haven't tested it, but this might work:

alert(this.options[this.selectedIndex].innerHTML)
like image 42
Brian Driscoll Avatar answered Oct 01 '22 10:10

Brian Driscoll


This will work.

select = document.getElementById("select");
select.onchange = function(){
    alert(this.value); //returns the selected value
    alert(this.innerHTML); //returns the entire select with all the options
    var options = this.getElementsByTagName("option");
    var optionHTML = options[this.selectedIndex].innerHTML;  
    alert(optionHTML); //this is what I want, but it works now
};
like image 40
Matt Howell Avatar answered Oct 01 '22 11:10

Matt Howell


After doing some research it appears as though the browser (Chrome anyway) will strip out tags from option values making it impossible to get the actual HTML code. For example, given the following HTML:

<html>
  <body>
    <select>
      <option><b>test 1</b></option>
      <option><b>test 2</b></option>
    </select>
  </body>
</html>
  • document.getElementsByTagName('select')[0].options[0].text returns 'test 1'
  • document.getElementsByTagName('select')[0].options[0].innerHTML returns 'test 1'
  • document.getElementsByTagName('select')[0].options[0].firstChild returns a text node containing 'test 1'
  • document.getElementsByTagName('select')[0].firstChild.nextSibling returns the first option node. Its first child is the text node 'test 1'
like image 39
Bryan Kyle Avatar answered Oct 01 '22 11:10

Bryan Kyle