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

前端 未结 4 513
花落未央
花落未央 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 06:56

    Modern browsers support the Selectors API (through querySelector), which lets you do this very easily:

    document.querySelector("#id_name > .classname > textarea").value = "foo";
    

    For completeness, I should mention that this will operate on the first element that matches the selector (you can also tweak the selector of course). If there is the possibility of having many elements that need to be targeted, you can switch to querySelectorAll and a loop.

提交回复
热议问题