document.getElementById("#foo"); returns null - javascript

I am trying to create a media player.
I am not sure why my call to document.getElementById("#playlist-table"); returns null when I have in my HTML <table id="playlist-table"></table>. I have tried running the script just before the </body> tag to make sure the DOM was ready, and still no luck. Here is my code:
HTML(shortened)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>JAMTRACKS</title>
<script type="text/javascript" src="js.js"></script>
</head>
<body>
<div id="media-player">
<div id="playlist">
<table id="playlist-table"></table>
</div>
</div>
</body>
</html>
JS(shortened)
function addTrack(title){
var table = document.getElementById("#playlist-table");
var tr = document.createElement("tr");
var titleTd = document.createElement("td");
var titleNode = document.createTextNode("title");
table.appendChild(tr); //ERROR IS HERE
tr.appendChild(titleTd);
titleTd.appendChild(titleNode);
...
}
addTrack(Song_Name);
Error : Uncaught TypeError: Cannot read property 'appendChild' of null
Thank you

remove the hashtag # from the selector
var table = document.getElementById("playlist-table");
if you want to keep it, you should use querySelector()
document.querySelector('#playlist-table')

Correct ways to query for id:
document.getElementById('foo');
or
document.querySelectorAll('#foo');
Returns the first element:
document.querySelector('#foo');

^^
var table = document.getElementById("playlist-table");

Related

Keep Getting an error in javascript about a node

so im trying to make a list of the input from the user and i keep getting this error
html
<!DOCTYPE html>
<html lang="en">
<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>ToDo</title>
</head>
<body>
<h1>To Do List</h1>
<label>Enter What You Have To Do:</label>
<br>
<br>
<input type="text" id="toDo">
<br>
<br>
<button type="button" id="myButton">Submit</button><br>
<ul id="list"></ul>
<script src="todojs.js"></script>
</body>
</html>
javascript
document.getElementById('myButton').onclick = function () {
const doIt = document.getElementById('toDo').value;
const li ='<li>' + doIt + '</li>';
document.getElementById('list').appendChild(li);
document.getElementById('toDo').value = '';
}
Error
Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
at document.getElementById.onclick
appendChild expects a Node Element. You are passing a string.
If you want to append a string, you can use the insertAdjacentHTML function.
https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
document.getElementById('myButton').onclick = function () {
const doIt = document.getElementById('toDo').value;
const li ='<li>' + doIt + '</li>';
document.getElementById('list').insertAdjacentHTML('beforeend', li);
document.getElementById('toDo').value = '';
}
const li = document.createElement("li");
li.innerHTML(doIt);
should do the trick instead of the one liner
if you pass a string, that string isn't a node or a real element present in the DOM, it wouldn't work.
so simply just programmatically create one element! using document.createElement()
change the text inside it, using document.textContent
try to not use innerHTML because is DANGEROUS, someone can insert in the input some malicious code scripts. textContent is more safe
one more thing, use .addEventListener()
instead of .onclick,
because if you have more event listener in one time, .onclick sometimes don't work, with .addEventListener() you can make 2 or more events work in one time.
for inserting before you can use this: https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore , just read the documentation I linked to you, and you are done!
I hope this help you!
one more thing:
if you want more custom UI,
you can write a copy of all your elements inside a <div>,
and then insert it inside a <template> tag manually...
the result is: now you have a reusable component with just regular HTML, JS
so the previus document.createElement(); it will become Node.cloneNode()
more details here: https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode
let btn = document.getElementById('myButton');
let list = document.getElementById('list');
let inputEl = document.getElementById('toDo');
btn.addEventListener('click', () => {
const getliValue = inputEl.value;
const newLi = document.createElement('li');
newLi.textContent = getliValue;
list.appendChild(newLi);
inputEl.value = '';
});
<h1>To Do List</h1>
<label>Enter What You Have To Do:</label>
<br><br>
<input type="text" id="toDo">
<br><br>
<button type="button" id="myButton">Submit</button>
<br>
<ul id="list"></ul>
<script src="script.js"></script>

How can I make a variable be the select Id in a getElement

How can I make a variable be the select Id in a getElement? When I tried it, it returned null. My code is shown below:
<html>
<head>
</head>
<body>
<p id = "test">hi</p>
<script>
var test = "test";
document.getElementById(test).innerHTML = "complete";
</script>
</body
</html>
That code seems to work just fine (with the exception of the unclosed body tag), here is a runnable version of the code, fixed:
<html>
<head>
</head>
<body>
<p id = "test">hi</p>
<script>
var test = "test";
document.getElementById(test).innerHTML = "complete";
</script>
</body>
</html>
Remember, the js code is going to happen almost immediately, so you won't be able to see the "hi" part. If you want it to change after like 1 second, use this:
<html>
<head>
</head>
<body>
<p id = "test">hi</p>
<script>
var test = "test";
setTimeout(function () {
document.getElementById(test).innerHTML = "complete";
}, 1000);
</script>
</body>
</html>
All I changed in that, is put the document.getElementById() into a setTimeout
Hope this helped.

How to reduce javascript code that use JQuery and .each()

I have tried to reduce following code
var wgDialog
= jQuery(".ui-dialog.ui-overlay-visible",window.parent.document)
.each
(function(nIndex)
{
var sWidgetName = $(this).attr('data-widgetvar');
var wgDialog = window.parent.PF(sWidgetName);
});
to this code
var jqDialog
= jQuery(".ui-dialog.ui-overlay-visible",window.parent.document)
.children(":first-child");
var sWidgetName = jqDialog.attr('data-widgetvar');
var wgDialog = window.parent.PF(sWidgetName);
but this doesn't work !
The sWidgetName variable is always undefined in last code.
What is my mistake ?
With help of comments, I have found a solution.
I must use get(0) to obtain first element in list returner by JQuery().
And I must use $(jqDialog) instead of jqDialog to get 'data-widgetvar' attribute.
Here is my new code
var jqDialog
= jQuery(".ui-dialog.ui-overlay-visible",window.parent.document)
.get(0);
var sWidgetName = $(jqDialog).attr('data-widgetvar');
var wgDialog = window.parent.PF(sWidgetName);
Assuming you want to access an element with attribute data-widgetvar nested in an element having css classes ui-dialog and ui-overlay-visible you could do the following with plain javascript:
var myElement = document.querySelector('.ui-dialog.ui-overlay-visible [data-widgetvar]');
querySelector allows a CSS like selector combining class together with attribute selector.
Update:
Here is a working example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Test</title>
<script type="text/javascript">
function main() {
var myElement = document.querySelector('.ui-dialog.ui-overlay-visible [data-widgetvar]');
console.log("Attribute value", myElement.getAttribute('data-widgetvar'));
}
document.addEventListener("DOMContentLoaded", main);
</script>
</head>
<body>
<div class="ui-dialog ui-overlay-visible">
<div>some element</div>
<div data-widgetvar="someValue">some text content</div>
</div>
</body>
</html>

how to get innerHTML value in javascript code

I want to change table <td> data by using innerHTML property. But after applying innerHTML property those values set in <td> are not accessible in Javascript code.
So is there any alternative to innerHTML property so that value can be set in <td> and it can also be accessed in Javascript Code.
Javascript code
<script>
var row=0,col=0,i=1;//can be used in loop
document.getElementById("tableID").rows[row].cells[col].innerHTML=i;
</script>
Look at this small sample, innerHTML works. Walk with cursor keys through the Table. Show us more Code
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Table key´s</title>
<style>
td{width:40px;height:40px;background:#ddd;}
</style>
</head>
<body>
<div id="tableContainer">
</div>
<script>
var aktRow=aktCol=4,max=9;
tableContainer.innerHTML = '<table id="mt">'+('<tr>'+'<td></td>'.repeat(max+1)+'</tr>').repeat(max+1)+'</table>';
mt.rows[aktRow].cells[aktCol].style.background='#f00';
window.addEventListener("keyup", function(e){
var colDiff, rowDiff;
var keyMap = new Map([[37,[-1,0]],[38,[0,-1]],[39,[1,0]],[40,[0,1]]]);
if (keyMap.has(e.keyCode)){
mt.rows[aktRow].cells[aktCol].style.background='#ddd';
mt.rows[aktRow].cells[aktCol].innerHTML=aktRow+'-'+aktCol;
console.log(mt.rows[aktRow].cells[aktCol].innerHTML);
[colDiff,rowDiff]=keyMap.get(e.keyCode);
aktRow+=rowDiff;
aktCol+=colDiff;
aktRow = (aktRow>max) ? max : (aktRow < 0) ? 0 : aktRow;
aktCol = (aktCol>max) ? max : (aktCol < 0) ? 0 : aktCol;
mt.rows[aktRow].cells[aktCol].style.background='#f00';
}
})
</script>
</body>
</html>
your code is wrong here
.rows[row].cells[col]
This is what i suggest:
set an id for each cell, something like col1row1 as id, then access the cell by id:
document.getElementById("col1row1").innerHTML = i
or have a for loop go through each row and cell with getElementsByType('td').innerHTML = i for example
take a look at this :
Iterating through a table with JS

Replacing inner HTML fails despite onload function

I rarely have to do any Javascript and I seem to fail doing the easiest tasks. I am trying to replace a string in two divs. The first div gets replaced, the second one is not found with the error message:
drawings.html:20 Uncaught TypeError: Cannot set property 'innerHTML' of null
However I tried the usual remedies of putting my code in an 'onload' function and putting the script at the end of the body tag. What else could possibly go wrong?
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="cell1">test<div>
<div id="cell2">test<div>
<script>
window.onload = function() {
replace();
}
function replace() {
console.log("replace");
document.getElementById("cell1").innerHTML = "cell1";
document.getElementById("cell2").innerHTML = "cell2";
}
</script>
</body>
</html>
just close your divs elements.
<html>
<head>
</head>
<body>
<div id="cell1">test</div>
<div id="cell2">test</div>
<script>
window.onload = function() {
replace();
}
function replace() {
console.log("replace");
document.getElementById("cell1").innerHTML = "cell1";
document.getElementById("cell2").innerHTML = "cell2";
}
</script>
</body>
</html>

Categories