user3547286
user3547286

Reputation: 15

HTML DOM Javascript not working?

I have a drop down menu that, when clicked, successfully changes the image's thumbnail. But, I also need the <p> text to change. I looked at W3Schools, and still to no avail. Here is my code.

<p id="caption"></p>
<select name="woodType" id="woodType" onChange="changeThumbnail();changeCaption(this);">

<script>
    function changeCaption(selTag) {
        var caption = selTag.options[selTag.selectedIndex].text;
        document.getElementById("caption").text = "Wood: " + caption;
    }
</script>

The text will NOT change.

Upvotes: 1

Views: 3011

Answers (3)

potashin
potashin

Reputation: 44581

Try the following :

 <script>
     function changeCaption(selTag) {
         var caption = selTag.value;
         document.getElementById("caption").innerHTML = "Wood: " + caption;
     }
 </script>

You should use innerHTML property to set or return the text of the <p> element.

Upvotes: 5

Nipuna
Nipuna

Reputation: 7006

document.getElementById returns a reference to a DOM element. You can think of few candidates you can use on the Element object namely textContent, innerHTML and innerText (not working in Firefox)

If you read the article here and documentation on developer.mozilla.org you'll notice that its better use textContent than using innerHTML for your requirement.

In the Mozilla documentation for innerHTML under security considerations it says,

It is recommended you not use innerHTML when inserting plain text; instead, use node.textContent. This doesn't interpret the passed content as HTML, but instead inserts it as raw text.

Upvotes: 0

Deepak Ingole
Deepak Ingole

Reputation: 15742

.text is property of option elements not p.To set p text you should be using .innerHTML,

function changeCaption(selTag) {
    var caption = selTag.options[selTag.selectedIndex].text;
    document.getElementById("caption").innerHTML = "Wood: " + caption;
}

DEMO

Upvotes: 1

Related Questions