How to set a value of the textarea without id by javascript?

前端 未结 4 509
花落未央
花落未央 2021-01-13 06:26

Typically we run javascript code to set any value:

document.getElementById(\'id_name\').value = \"...\";

But I have a page like this:

4条回答
  •  滥情空心
    2021-01-13 07:15

    You can use the DOM properties and methods to get to that element from any fixed point (for instance, from your div that does have an id). In your case, it's dead easy:

    document.getElementById('id_name').firstChild.firstChild.value = /* ... */;
    

    ...assuming that you've formatted that HTML for us and it really looks like this:

    If that assumption isn't valid, then you have to do more work, because the firstChild may well be a Text node (containing the white space) rather than an Element. If so, it's still pretty easy with a helper function:

    function firstElement(node) {
        while (node && node.nodeType !== 1) { // 1 = Element
            node = node.nextSibling;
        }
        return node;
    }
    
    var n = document.getElementById("id_name");
    n = firstElement(n);
    n = firstElement(n);
    n.value = /* ... */;
    

    This is why so many JavaScript DOM manipulation libraries have sprung up: Because common use-cases are frequently awkward when the DOM is used directly.

    References:

    • DOM2 Core
    • DOM2 HTML
    • DOM3 Core
    • HTML5 Section 3 ("Semantics, Structures, and APIs of HTML documents")

提交回复
热议问题