Could someone help me with this javascript code - javascript

Hello i was learning Javascript from 10 day of javascript videos and in last day it still runs error: Uncaught TypeError: Cannot read property 'insertAdjacentHTML' of null
could someone help me
let ourForm = document.getElementById('ourForm')
let ourField = document.getElementById('ourField')
let ourList = document.getElementById('ourList')
ourForm.addEventListener('submit', (e) => {
e.preventDefault()
createItem(ourField.value)
})
function createItem(x) {
ourList.insertAdjacentHTML('beforeend', x)
}

This will be because the element with an id of ourList does not exist. Double check you have an element in your HTML with this id.

Please recheck your HTML code. It looks like you missed the id ourList somewhere. The error means that your javascript was unable to find the element with the given id.

If you check your HTML code, there must be an element with an id of "ourList" for your code to work. Since the error says that an object with that id currently returns a null, something is incorrect. You most likely either misspelled it, or forgot to add the id to the corresponding HTML element.
You do this by writing:
<ul id="ourList"> ... </ul>
where ul is your element type. (ul, ol, div...)

Related

Access multiple elements with ID from within a node, but also with specific class

I need to retrieve all elements who's ID ends with "_inputError" from within a specific element! AND also , I need to retrieve only the inputError that has class 'b-block' set.. How would I do this using javascript/jquery ?
I know I can get my form node with: var formNode = $("#frm1");
I know I can get ALL elements with ID ending, but this will get them all, which isn't quite what I need: var inputErrors = $("[id$=_inputError]");.
How do I mix'em all together as to retrieve only the input errors with 'd-block' class from within a specified form node ?
Cheers!
UPDATE: This seems to work for me:
var inputErrors = $("[id$=_inputError].d-block");
console.warn(inputErrors[0]);
It'll retrieve all inputError with class .d-block. However, I've yet to find how to do this check ONLY from a selected form element id, instead of the hole page. (I can have multiple forms on a single page!)
To help others if it can, here's the final solution and why I needed this:
Essentially, I get a response back from an ajax post like so:
{
type: 2,
formid: 'frmProfile',
fields: {
username: "Invalid username!",
email: "Invalid email!"
}
}
I loop my response.fields to show the individual errors under each failed inputs.
I then needed to find a way set focus on the first failed input! Because my fields are NOT 0-indexed based, I could not simply set the focus on the first field in the array! They are 'randomly' looped through!
Therefor, I decided to get all input errors that we're showing (id=*_inputError and with class d-block). The first one in the returned array is in fact the first input error! So, I use its ID to determine the corresponding input name and set focus to it:
var inputErrors = $("#" + response.formid + " [id$=_inputError].d-block");
var firstInputError = inputErrors[0].id.replace(/_inputError$/, ''); // get just the name of the failed input! Its name/id should be the same as <name>_inputError!
document.getElementById(firstInputError).focus();
This seems to do the trick for me ;) Hopefully, this can serve ideas to others.
Thanks for your help folks!
P

appendChild inside a newly created div

I can't understand why I am getting this error:
Uncaught TypeError: Cannot read property 'appendChild' of undefined
Here is my code:
//create new div element, append it to the body, give it an ID and a Class.
const container_clause_1 = document.createElement("div");
document.body.appendChild(container_clause_1);
container_clause_1.setAttribute("id", "container_clause_1");
container_clause_1.classList.add("cc1");
console.log(container_clause_1);
//returns <div id="container_clause_1" class="cc1></div>"
const cClause1 = document.getElementById("container_clause_1");
console.log(cClause1);
//returns <div id="container_clause_1" class="cc1></div>"
const right_clause_1 = document.createElement("div");
console.log(right_clause_1); //returns <div></div>
document.cClause1.appendChild(right_clause_1); //Error occurs here!
I don't understand what is undefined in this situation. cClause1 is define. right_clause_1 is also defined. Granted, it's an empty div at this point, but that is what I am trying to do - add the div and then I can add the class and id, etc.
Also, I don't see any typos.
Also, if I replace document.cClause1.appendChild(right_clause_1);
with document.body.appendChild(right_clause_1); it works fine. Except that I don't want it inside the body, but rather, inside the container_clause_1 div.
I can't use JQuery for this. "Why not" is not really germane to the question. I have my reasons. Just understand that I can't use JQuery.
Well that was so obvious - after everyone started pointing out what I did wrong! Thanks for the answers!
Just another thing that this pointed out to me:
I can eliminate the variable cClause and just use container_clause_1
so my code is shorter!
const container_clause_1 = document.createElement("div");
document.body.appendChild(container_clause_1);
container_clause_1.setAttribute("id", "container_clause_1");
container_clause_1.classList.add("cc1");
const right_clause_1 = document.createElement("div");
container_clause_1.appendChild(right_clause_1);
right_clause_1.setAttribute("id", "right_clause_1");
right_clause_1.classList.add("r1");
Why have "document." in this line?
document.cClause1.appendChild(right_clause_1);
Surely you only need:
cClause1.appendChild(right_clause_1);

getElementsByTagName inside GetElementById (object xraywrapper)?

I am trying to get a div that is inside another div, since the id of the second div is variable, i use
var wrappingdiv = document.getElementById('divId')
to get the wrapping div then
var insidediv = wrappingdiv.getElementsByTagName('div')
but i get the getElementsByTagName is not a function error, i guess the syntax is wrong, could you guys put me in the right direction?
Thanks in advance.
Edit : I will correct myself, I am trying to get the body of a gmail email, so :
var element = content.document.getElementsByClassName("ii gt m13fbe3a51e95e196 adP adO");
it returns an object xraywrapper[object htmlcollection]
Edit 2 :
I am using mozilla firefox, and i am developing my own extension, to access source code of Google mail i use simple javascript (content.document...)
If you doesn't have any element with the id divId then wrappingdiv will be equal null:
And when trying to get null.getElementsByTagName you will get a type error:
TypeError: Cannot read property 'getElementsByTagName' of null
In
var element = content.document.getElementsByClassName(
"ii gt m13fbe3a51e95e196 adP adO");
getElements <- the s means this returns multiple elements (in a list-like collection), not just one element.
You might just want to pick out the first one it found.
var element = content.document.getElementsByClassName(
"ii gt m13fbe3a51e95e196 adP adO")[0];
There is also a small risk that it might not be m13fbe3a51e95e196 on every page, or forever. So perhaps you should generalise your search a bit. How about just searching for class "adP"?
The syntax isn't wrong. document.getElementById('divId') probably just fails to match the id of any existing element, so it returns null (which doesn't have a getElementsByTagName method).
DEMO
var wrappingdiv = document.getElementById("divId");
var insidediv = wrappingdiv.getElementsByTagName('div');
var i = 0;
for(i=0;i<insidediv.length;i++)
alert(insidediv[i].innerHTML);

Cannot get document.getElementByID to work

The following function doesn't work for some reason. Can someone see what the problem is?
function checkMaxLen(txt, maxLen) {
var actualLen = txt.value.length;
var remain = maxLen - actualLen;
document.getElementById('remainChar').Value = remain;
}
<input type="text" id="remainChar" runat="server" value="500"/>
Whenever I try to run the function, I get this error:
Microsoft JScript runtime error: Unable to set value of the property 'Value': object is null or undefined
Check the ID of the input in your final HTML. Since you have runat="server" ASP.NET is likely adding its typical container prefixes.
Main Problem: There is no Javascript getElementById issue, but rather a problem with feeding the right id into getElementById (caused because ASP.NET feels free to change the ids of runat="server" elements) (covered by the accepted answer). This is what caused the error the OP reported:
Microsoft JScript runtime error: Unable to set value of the property 'Value': object is null or undefined
This was because getElementById was given a non-existent id and returned null.
Another Problem: The second problem was indeed a Javascript problem, but not related to getElementById either. Javascript is case sensitive, so trying to set the value property of a input element's DOM object cannot be done by trying to set But even if the (non-existent) Value property.
Solution:
The correct code that solves both problems follows:
function checkMaxLen(txt, maxLen) {
var actualLen = txt.value.length;
var remain = maxLen - actualLen;
document.getElementById('<%= remainChar.ClientId%>').value = remain
}
Note: Thanks go to Ian for pointing out an important oversight in my original answer.
case sensitive:
document.getElementById('remainChar').value
.Value should be .value, script should be executed after appears in the source or after the DOMReady event has been fired.
also since this is asp.net the id attribute of the box will not be "remainChar" but transformed into something else.
so you either need to find out what the final id will be or remove the runat="server" attribute
<html>
<body>
<input type="text" id="remainChar" value="500"/>
<script>
function checkMaxLen(txt, maxLen) {
var actualLen = txt.value.length;
var remain = maxLen - actualLen;
document.getElementById('remainChar').value = remain;
}
checkMaxLen({value:""},20);
</script>
</body>
</html>

why this Javascript code not working

Below is simple code I am using. But why it's not working. giving javascript error.
function postcommnet(wallid) {
var txtboxid='commentdata_'+wallid;
var commentdata=document.getElementById(txtboxid).value
}
error is : document.getElementById(txtboxid) is null.
Please help.
This is one of the few cases where the error is telling you what's wrong:
"document.getElementById(txtboxid) is null."
This means, essentially, that the value of the above is null. This means that getElementById did not find an element with the ID you provided.
Check that the value of txtboxid is correctly an id on one of the DOM's elements. Your error message means that the element is not retrieved and thus the value is null.
It cannot find the element with the id. I have checked the code is working if there is an element with the given id.
This actually works:
<html>
<body>
<input value="lol" id="commentdata_1"/>
<script type="text/javascript">
function postcomment(wallid) { var txtboxid='commentdata_'+wallid;
var commentdata=document.getElementById(txtboxid).value
}
postcomment(1);
</script>
</body>
</html>
The id may not exist on your page, its worth checking.
The following checks to see if the id exists. If it does not exist it will tell you the id its trying to use.
function postcommnet(wallid) {
var txtboxid='commentdata_'+wallid;
if(document.getElementById(txtboxid)){
var commentdata=document.getElementById(txtboxid).value
}
else{
alert('the id - ' + txtboxid +' does not exist');
}
}
I'd suggest using Firefox/Firebug and setting a breakpoint inside your function, then check that the value for wallid is what you expect and, if necessary, examine the live HTML to ensure that the element does, in fact, exist.

Categories