简体   繁体   中英

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;
            }
        }
    };

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";
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM