I am trying to practice Javascript but I am getting the
document.getElementById(...) is null error. I am not sure why it is not working. ........................................................................................................................................................................................................................................
<!DOCTYPE html>
<html>
<title></title>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body style="max-width: 960px; margin: 0px auto; background-color: green;">
<section id="practice">
</section>
</body>
<script>
window.onload = function create() {
var newDiv = document.createElement('div');
var newp = document.createElement('p');
var pTextNode = document.createTextNode('First time creating elements on my own.');
newDiv.className = 'contentContainer';
newDiv.id = 'container1';
newDiv.setAttribute('title', 'hello');
newp.appendChild(pTextNode);
newDiv.appendChild(newp);
document.getElementById("#practice").appendChild(newDiv);
}
</script>
</html>
The document.getElementById API takes an ID parameter as a string. You don't need to use the CSS selector method of selecting IDs, so the # should be omitted. The line should read:
document.getElementById("practice").appendChild(newDiv);
For more information about the API, see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
You have it all correct! The issue is your syntax in the getElementById method. Remove the octothorpe ("#") and you'll get the results you're expecting.
Happy Coding!
Related
I've got this error:
index.js:29 Uncaught TypeError: clone.getElementById is not a function
at HTMLButtonElement.changeImg (index.js:29:11)
changeImg # index.js:29
It marks the line highlighted. I don't understand why. If somebody can help me I'll appreciate it.
//captura de elementos:
const btn = document.querySelector('.btn');
const templateImg = document.querySelector('.templateImg').content;
const imgContainer = document.querySelector('.imgContainer');
const fragment = document.createDocumentFragment();
let arrayImg = [
"/img/food1.jpg",
"/img/food2.jpg",
"/img/food3.jpg",
"/img/food4.jpg",
"/img/food5.jpg",
"/img/food6.jpg",
"/img/food7.jpg",
"/img/food8.jpg",
"/img/food9.jpg"
];
const changeImg = () => {
let ran = Math.floor(Math.random() * 9);
//Crear clon del template:
const clone = templateImg.firstElementChild.cloneNode(true);
console.log(clone);
console.log(arrayImg[ran]);
//capturar elemento y modificar el src:
clone.getElementById("img").src = arrayImg[ran];
fragment.appendChild(clone);
imgContainer.appendChild(fragment);
}
btn.addEventListener('click', changeImg);
<!DOCTYPE html>
<html lang="es">
<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">
<link rel="StyleSheet" href= "style.css" type= "text/css">
<title>Cambiador de imagenes</title>
</head>
<body>
<div class="container">
h1>Food and drink in Florianopolis</h1>
<div class="imgContainer"><!--templateImg--></div>
<button type="text" class="btn" id="btn">Change</button>
</div>
<template class="templateImg">
<img id="img" src="/img/food1.jpg">
</template>
<script src="./index.js"></script>
</body>
</html>
I was trying to change the images inside the template modifying the src:
<template class="templateImg">
<img id="img" src="/img/food1.jpg">
</template>
When I use querySelector, the error is that the value I try to replace is null even though it's not, and with getElementById, I get that message that it's not a function.
you create a "clone" with this code:
const clone = templateImg.firstElementChild.cloneNode(true);
that is a image element(see in console) and you for changing image src just need to use this code:
clone.src = arrayImg[ran];
getElementById() is a method of document not of any HTML element.
What you want to use instead is querySelector which you can in fact use on elements.
I know this gets asked a lot and I've already tried some examples from SO, but no luck.
I have a function that allows me to change text in a div and it works, but only as plain text. I want it to work as HTML, but I've tried placing in innerHTML, perhaps in the wrong spot, and separated HTML in my script with + symbols. Nothing seems to work. Either I get the HTML in my text raw or the function simply does not work.
Here's my script as of this time:
$(function() {
var copyStack = [
'<strong>This is bold text within strong tags,</strong>' + ' this is the remainder of my copy.',
'<strong>This is more bold text within strong tags,</strong>' + ' this is the remainder of my second copy.'
];
$("#swatch-0").click(function () {
$(".product-shop-description").text(copyStack[0]);
console.log(copyStack[0]);
});
$("#swatch-1").click(function () {
$(".product-shop-description").text(copyStack[1]);
console.log(copyStack[1]);
});
});
I think This is what you want to do:
var copyStack = [
'<strong>This is bold text within strong tags,</strong>' + ' this is the remainder of my copy.',
'<strong>This is more bold text within strong tags,</strong>' + ' this is the remainder of my second copy.'
];
swatchOne = document.getElementById("swatch-0");
const changeInnerHTML = (elm, inner) => (elm.innerHTML = inner);
swatchOne.addEventListener("click", () => {
changeInnerHTML(swatchOne,copyStack[0]);
});
swatchTwo = document.getElementById("swatch-1");
swatchTwo.addEventListener("click", () => {
changeInnerHTML(
swatchTwo,copyStack[1]);
});
.btn{
background: #cecece;
padding: 1em;
width: max-content;
margin-bottom:1em;
}
#swatch-0{
background: #000;
color:#fff
}
<!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>Document</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class='btn' id='swatch-0' >Hello</div>
<div class='btn' id='swatch-1' >Hello22</div>
<script src="./script.js"></script>
</body>
</html>
The getElementById property is used to access an HTML element
more info [HERE][]
The innerHTML property is used to access and modify the HTML inside of an HTML element
more info HERE
Solved it! Thanks to some help and some guesswork, here's the answer:
$("#swatch-0-peanut-butter-chocolate-chip").click(function () {
$(".product-shop-description").html(copyVariety[0]);
console.log(copyVariety[0]);
});
Ok, so all I want to do is : whenever I write something in the Input and press the Button, a new HTML page gets created. But I also want to set the page's name and location. Tried searching it, couldn't find any results...
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Books test</title>
<link rel="stylesheet" href="https://cdn.rawgit.com/Chalarangelo/mini.css/v3.0.1/dist/mini-default.min.css">
</head>
<body>
<input type="text" id="book-input">
<button id="book-button">Create a book</button>
<h1>All the books</h1>
<ul id="books-list"></ul>
<script src="/app.js" defer></script>
</body>
</html>
Javascript
const bookNameInput = document.getElementById("book-input");
const bookCreateButton = document.getElementById("book-button");
var bookName;
var bookId;
bookCreateButton.addEventListener('click', createBook);
function generateRandomNumber() {
var randomNumber = Math.floor(1000000000 + Math.random() * 900000000);
var rn = randomNumber.toString();
return rn;
}
function createBook() {
bookName = bookNameInput.value;
bookId = generateRandomNumber();
fbn = bookName + '_' + bookId
var bookLi = document.createElement("li");
bookLi.classList.add("book-li")
var bookLiA = document.createElement("a");
bookLiA.innerText = bookName;
bookLiA.href = fbn + ".html";
document.getElementById("books-list").appendChild(bookLi);
bookLi.appendChild(bookLiA);
bookNameInput.value = "";
}
Tried using :
const newDoc = document.implementation.createHTMLDocument(title)
But doesn't creates any page...
I already answered your question in comments, so I'm writing this down as a answer so it might be helpful for others too.
So as i was saying it is totally possible to save the file directly from the client side without any need of server or special file system permission on client side -
In Short You can do something like this, Follow this step-by-step -
Get the value of the text input using input.value
Create a Blob out of It
Create a DOM element of anchor element with download attribute
Convert the Blob to an URL Using URL.createObjectURL and Chane the href of previously created anchor element to the returning url
Click on the anchor element without appending it to the DOM
Here is the Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Generate HTML Page</title>
<style>
* {
padding: 0;
box-sizing: border-box;
margin: 0;
}
</style>
</head>
<body style="padding: 20px">
<textarea
placeholder="Enter Your Content Here"
style="width: 100%; height: 500px; font-size: 18px; padding: 18px"
></textarea>
<br /><br />
<button>Download Text as HTML page</button>
<script>
let btn = document.querySelector("button");
let text = document.querySelector("textarea");
btn.addEventListener("click", () => {
if (!/^\s*$/.test(text.value)) {
let a = document.createElement("a");
a.setAttribute("download", "download.html");
let blob = new Blob(text.value.split(""));
let url = URL.createObjectURL(blob);
a.href = url;
a.click();
text.value = "";
} else {
alert("Blank text");
text.value = "";
}
});
</script>
</body>
</html>
I am attempting to change the backgroundColor of "gridElement" once "button" is clicked.
What was attempted, changing the way the elements are created to later include the event:
cloneNode() // doesn't work with eventListeners unless you use eventDelegation, in this case there is no parentElement to delegate the event too.
jQuery.clone() // the event is not tied directly to "gridElement" rather it is tied to "button" so jQuery.clone() would not be deep copying any associated events.
Also, attempting to make references to all gridElements:
used window.globalVarRef = localVar. // only references the first element and not all.
How can I modify the code so that the eventListener will change all "gridElement" and not just the first?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="CSS/main.css">
<title> Method 1 // appendChild() </title>
</head>
<body>
<div id="container">
<div id="gridContainer"></div>
</div>
<script>
const gridContainer = document.getElementById('gridContainer');
function createPixels(){
let pixels = 256;
for(let k=0;k<pixels;k++) {
const gridElement = document.createElement('div');
gridElement.classList.add('gridElement');
gridContainer.appendChild(gridElement);
window.allGridElements = gridElement;
}
}
createPixels();
const button = document.createElement('button');
button.classList.add('button');
button.textContent = 'button';
gridContainer.appendChild(button);
function changeBkg(){
window.allGridElements.style.backgroundColor = 'blue';
}
button.addEventListener('click', changeBkg);
</script>
</body>
</html>
The problem lies in your changeBkg function. To select all of the elements with the class of "gridElement", you want to use a for loop to find those elements and then change their styles. I added some basic css to the grid element so we can see the color change in action. Does that solve your issue?
.gridElement {
width: 100px;
height: 100px;
background: red;
display: inline-block;
margin-right: 10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="CSS/main.css">
<title> Method 1 // appendChild() </title>
</head>
<body>
<div id="container">
<div id="gridContainer"></div>
</div>
<script>
const gridContainer = document.getElementById('gridContainer');
function createPixels(){
let pixels = 256;
for(let k=0;k<pixels;k++) {
const gridElement = document.createElement('div');
gridElement.classList.add('gridElement');
gridContainer.appendChild(gridElement);
window.allGridElements = gridElement;
}
}
createPixels();
const button = document.createElement('button');
button.classList.add('button');
button.textContent = 'button';
gridContainer.appendChild(button);
function changeBkg(){
var items = document.getElementsByClassName('gridElement');
for (let i=0; i < items.length; i++) {
items[i].style.backgroundColor = 'blue';
}
}
button.addEventListener('click', changeBkg);
</script>
</body>
</html>
I have a problem with simple thing.
I want to add a element into html div tag using createElement Method. I have tried a lot of diferent ways but always getting the same result - nothing happens.
This is my code:
function changeReleaseDate()
{
var parentElement = document.getElementByClassName("container body-content");
var existingElement = document.getElementByClassName("btn btn-default");
var newInput = document.createElement("input");
newInput.type = "text";
newInput.className = "form-control";
parentElement.insertBefore(newInput, existingElement);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My ASP.NET Application</title>
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
<script src="script.js"></script>
</head>
<body>
<div class="container body-content">
<h2>Index</h2>
<button id="btn" type="button" onclick="changeReleaseDate()" class="btn btn-default">Default</button>
<hr />
<footer>
<p>©My ASP.NET Application</p>
</footer>
</div>
</body>
</html>
I also tried to use appendChild but in this case input field was placed out of div.
The problem is that getElementByClassName should be getElementsByClassName.
This method returns a HTMLCollection, so to access the first element from this list you need to use bracket with index 0:
var parentElement = document.getElementsByClassName("container body-content")[0];
var existingElement = document.getElementsByClassName("btn btn-default")[0];
Demo: http://jsfiddle.net/jak4efau/
However it's more convenient in your case to use querySelector method:
var parentElement = document.querySelector(".container body-content");
var existingElement = document.querySelector(".btn.btn-default");
Also note, that you need to take care of the case when user clicks button multiple times, you probably don't want to append multiple input fields.