Home > Mobile >  Accessing an element in a form that has no id in javascript
Accessing an element in a form that has no id in javascript

Time:05-12

I have an assignment as a part of a cyber security course where I am supposed to submit a form with specific values for the inputs.

here is the relevant snippet of the source code I am working with is: (source code for a messaging system)

 <div >
    <label for="inputSubject">Subject:</label>
    <input name="subject" type="text"  id="inputSubject" placeholder="Enter a subject" pattern=".{5,}" required>
</div>
<div >
    <textarea name="contents"  rows="10" placeholder="Enter your message" pattern=".{5,}" required></textarea>
</div>

whenever I am trying to set the value of the textarea using either getElementsbyName or getElemetnsbyTagName, I get the error "Uncaught TypeError: Cannot set properties of null. Any idea how to fix this?

CodePudding user response:

Two things:

  1. Ensure you are correctly referencing the element
  2. Set with either value or textContent.
const textArea = document.querySelector('textarea[name="contents"]');
textArea.textContent = `whatever you want it to say`.

CodePudding user response:

Import a script in your html with this way <script defer src="script.js"></script> so that the DOM tree is created. In your imported script, you can do this: document.getElementsByTagName("textarea")[0].value = "Test Value";

CodePudding user response:

As a getElementsByName return a list of nodes and you only have one element with that name:

This should work for you:

document.getElementsByName("contents")[0].value = "hello world"

here how you could implemented:

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div >
        <label for="inputSubject">Subject:</label>
        <input name="subject" type="text"  id="inputSubject" placeholder="Enter a subject"
            pattern=".{5,}" required>
    </div>
    <div >
        <textarea name="contents"  rows="10" placeholder="Enter your message" pattern=".{5,}"
            required></textarea>
    </div>

    <script>
        document.getElementsByName('contents')[0].value = 'hello world'
    </script>
</body>

</html>

CodePudding user response:

First: Make sure your textarea does exist in the page, and then call your function, you can use window.onload or $(document).ready function. If your function is executed before textarea is rendered to page, you will get the null exception error.

Second: By all methods like getElements and not getElement (without s) please note -> it is plural and not singular.

var element = document.getElemetnsByTagName('div');

If you want to manipulate them, don't forget to access the Array.

element[0].value

and not

element.value

Hope it's helpful.

  • Related