Trevor Hutto
Trevor Hutto

Reputation: 2142

How to tell whether my element needs innerHTML or value

I am using JavaScript to run some AB tests on my site. I am able to change the text in my <button>'s with element.innerHTML = "Text that I want" but using that same strategy I cannot change the text in <input type="submit">'s.

Inversely, I can change the value of submit buttons using element.value = "Text that I want", but cannot change a <button>'s text in that way.

So my question is, how can I know which function needs to be used on a specific element so that I can create an algorithm that handles every type of element?

In short: How do I know whether to use element.innerHTML or element.value programmatically?

NOTE: jQuery is not allowed.

Example - Here is some code that takes a class name as input and changes the element throughout the page. Sometimes an <input> may have the identifying class, but sometimes it may be a <div>, <button> or <p>.

var execute = function(experimentName, variation){
        var elements = document.getElementsByClassName(experimentName);
        for (var j = 0; j < elements.length; j++) {
            if (typeof(variation) == "function")
            {
                variation.call(elements[j]);
            }
            else
            {
                elements[j].value = variation;
                //elements[j].innerHTML = variation;
            }
        }
    };

Upvotes: 3

Views: 655

Answers (2)

Emissary
Emissary

Reputation: 10148

If you are trying to do it in a generic way you could make an instanceof check against the input element's interface class:

if( element instanceof HTMLInputElement ){
    element.value = "foo";
} else {
    element.innerHTML = "foo";
}

Upvotes: 5

SLaks
SLaks

Reputation: 887867

The same way you know how to use that element in HTML in the first place.

innerHTML sets the element's contents; value sets the element's value="" attribute.

Upvotes: 2

Related Questions