Can't find DIV in JS - javascript

I'm creating a webPage, I need to get an element by ID, but when I try to do it, the element returned is a null object.
I think because the div that I want to get is added in the HTML code when I press a button, but my JS code is compiled when the page is loaded, so JS can't find the div... How can I select my div with JS?
<html><head><script>
function getDiv(){
var div = document.getElementById('div_name');
div.innerHTML = "SOMETHING"; //div is null
//<div id="div_name"></div> isn't added when the page is loaded
}
function addDiv()
{
var iDiv = document.createElement('div');
iDiv.id = 'div_name';
document.getElementsByTagName('body')[0].appendChild(iDiv);
}
</script></head>
<body>
<button onClick="getDiv()">GETDIV</button>
<!-- Pretend that with this button I add the div with 'div_name' in my HTML
page -->
<button onClick="addDiv()">ADDDIV</button>
</body></html>

Refer below code :-
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
function addDiv(){
var div = document.getElementById('div_name');
var isDivPresent = (div && (div !== null ));
if(isDivPresent){
return;
}
var createDiv = document.createElement("div");
createDiv.setAttribute("id", "div_name");
createDiv.style.backgroundColor = "lightblue";
createDiv.style.width='250px';
createDiv.style.height='300px';
document.getElementsByTagName('body')[0].appendChild(createDiv);
}
function getDiv(){
var div = document.getElementById('div_name');
var isDivPresent = (div && (div !== null ));
if(!isDivPresent) {
addDiv();
getDiv();
}else {
div.innerHTML = "SOMETHING";
}
}
</script>
</head>
<body>
<button onClick="addDiv()">ADDDIV</button>
<button onClick="getDiv()">GETDIV</button>
</body>
</html>

function getDiv(){
var div = document.getElementById('div_name');
div.innerHTML = "SOMETHING"; //div is null
}
function addDiv(){
if(!document.getElementById('div_name')){
var div = document.createElement("div");
div.id = 'div_name';
div.innerHTML = "Added Through add div";
document.body.appendChild(div);
}
}
<button onClick="getDiv()">GETDIV</button>
<button onClick="addDiv()">ADDDIV</button>

here is a code that works as you whish. The main differences is :
I used onclick as attribute name instead of onClick
function addDiv() {
var div = document.createElement('div');
div.id = 'div_name';
document.body.appendChild(div);
div.innerHTML = 'initial content';
}
function updateDiv() {
var div = document.getElementById('div_name');
div.innerHTML = 'new content';
}
<!DOCTYPE html>
<html>
<head></head>
<body>
<button onclick="addDiv();">add div</button>
<button onclick="updateDiv();">replace div content</button>
</body>
</html>

If you click the GETDIV button without clicking the ADDDIV button first, then the div you're looking for isn't anywhere in the document body. So I would change the getDiv() like so:
function getDiv(){
var div = document.getElementById('div_name');
if(!div) { // if div is not added yet, then add it
addDiv();
}
div.innerHTML = "SOMETHING"; //div is null
}

Related

Uncaught TypeError: Cannot read properties of null (reading 'appendChild')

I'm trying to insert a new Div and an img inside that div via JS. I made a Class that i will user later on with a function inside that should be called to use that function and insert the image. When doing this i constantly get Uncaught TypeError: Cannot read properties of null (reading 'appendChild') HTML and JS below:
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>Actividad 3</title>
<script type="text/javascript" src="actividad3.js"></script>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="style.css">
<body >
<h2>EXTRAS DISPONIBLES</h2>
</body>
</html>
JS
class extra {
precio = "10€";
url = "concha_azul.jpeg";
constructor(precio, url) {
this.precio = precio;
this.url = url;
}
getHTML = function () {
console.log("hello");
var newDiv = document.createElement("div");
newDiv.id = "x";
var div = document.getElementById("x");
var img = document.createElement("img");
img.src = "concha_azul.jpeg";
div.appendChild(img);
}
}
let miExtra = new extra();
miExtra.getHTML();
When you attempt to grab the 'newDiv' element by it's id it doesn't yet exist in the HTML document. You need to append the newDiv element to the page first and then you can retrieve it by it's id...
//Create new div
var newDiv = document.createElement("div");
newDiv.id = "x";
//Add div to html body
document.body.appendChild(newDiv);
//Get new div by it's id
var div = document.getElementById("x");
var img = document.createElement("img");
img.src = "concha_azul.jpeg";
div.appendChild(img);
Also to make things more simple you could just do this...
//Create new div
var newDiv = document.createElement("div");
newDiv.id = "x";
//Add div to html body
document.body.appendChild(newDiv);
//Add an image element to the div
var img = document.createElement("img");
img.src = "concha_azul.jpeg";
newDiv.appendChild(img);

Remove wrapper div from document.createElement

I've been stuck on this for the longest time and it's driving me nuts. I've tried a dozen different methods and can't figure out how to get it to work. Any help would be appreciated!! Thanks
Here's my code:
<script>
function runScript() {
//get parent of script element
var element = document.currentScript.parentElement;
//my html string that needs to be inserted inside the original div
var item = "<div>test1</div><div>test2</div>";
//My current method. this method works but creates another wrapper div. I need a way to remove the wrapper div or a different method altogether without any wrapper divs.
var z = document.createElement('div');
z.innerHTML = item;
element.appendChild(z);
}
</script>
<div id="main-wrapper">
<script>
runScript();
</script>
</div>
<script>
function runScript() {
//get parent of script element
var element = document.currentScript.parentElement;
//my html string that needs to be inserted inside the original div
var item = "<div>test1</div><div>test2</div>";
element.innerHTML = item;
}
</script>
<div id="main-wrapper">
<script>
runScript();
</script>
</div>
As you've tagged with jQuery, you can create the element as follow:
$(item);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function runScript() {
var item = "<div>test1</div><div>test2</div>";
$(document.currentScript.parentElement).append($(item));
}
</script>
<div id="main-wrapper">
<script>
runScript();
</script>
</div>
You can use the insertAdjacentHTML method.
<script>
function runScript() {
//get parent of script element
var element = document.currentScript.parentElement;
//my html string that needs to be inserted inside the original div
var item = "<div>test1</div><div>test2</div>";
element.insertAdjacentHTML('beforeend', item);
}
</script>
<div id="main-wrapper">
<script>
runScript();
</script>
</div>
Or use a template instead of a DIV.
<script>
function runScript() {
//get parent of script element
var element = document.currentScript.parentElement;
//my html string that needs to be inserted inside the original div
var item = "<div>test1</div><div>test2</div>";
var z = document.createElement('template');
z.innerHTML = item;
element.appendChild(z.content);
}
</script>
<div id="main-wrapper">
<script>
runScript();
</script>
</div>

Javascript: How to center multiple buttons that were created in Javascript using dynamically set CSS Style

I am trying to create a row of three buttons in Javascript using dynamically set CSS Style, but I am having difficulty trying to center the row of buttons in the middle of the page. This is with buttons that are currently not part of a div.
I have tried button.align = 'center'; with no success.
Here is the link to jsfiddle snippet.
HTML SKELETON
<head>
<meta charset="utf-8">
<title>Buttons</title>
</head>
<body>
<script>
</script>
</body>
</html>
JAVASCRIPT
var one, two, three;
function button(text) {
var button = document.createElement('button');
var buttonText = document.createTextNode(text);
button.appendChild(buttonText);
return button;
}
function buttonTest() {
one = button('one');
two = button('two');
three = button('three');
// put the buttons on page
document.body.appendChild(one);
document.body.appendChild(two);
document.body.appendChild(three);
}
buttonTest();
Link Here
var one, two, three;
function button(text) {
var button = document.createElement('button');
var buttonText = document.createTextNode(text);
button.appendChild(buttonText);
return button;
}
function buttonTest() {
one = button('one');
two = button('two');
three = button('three');
var divElem = document.createElement('div');
divElem.setAttribute('style', 'text-align:center;');
// put the buttons on page
//document.body.appendChild(one);
//document.body.appendChild(two);
//document.body.appendChild(three);
divElem.appendChild(one);
divElem.appendChild(two);
divElem.appendChild(three);
document.body.appendChild(divElem);
}
buttonTest();
A quick solution would be adding text-align : center to the body
var one, two, three;
function button(text) {
var button = document.createElement('button');
var buttonText = document.createTextNode(text);
button.appendChild(buttonText);
return button;
}
function buttonTest() {
one = button('one');
two = button('two');
three = button('three');
// put the buttons on page
document.body.appendChild(one);
document.body.appendChild(two);
document.body.appendChild(three);
}
buttonTest();
body {text-align: center;}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Buttons</title>
</head>
<body>
<script>
</script>
</body>
</html>

Javascript, I can't with the sun to reach the above items to a iframe

I have to create the effect of a popup using a DIV with DOM, I used an iframe, inside the frame is a form, I can not get rid of the div with Javascript in the submit button because the DOM sees only after the iframe his creation and not the div that contains it ... how should I do?
<html>
<body >
<h1>Title</h1>
</body>
</html>
//Global variable which contain reference to divPopup's element
var divPopup;
function hideDiv() {
window.alert("Content of DIV POPUP " + divPopup );
divPopup.className = "overlayHidden";
}
function load_page() {
var nodoDiv = document.createElement("DIV");
divPopup = nodoDiv;
nodoDiv.className = "overlay";
nodoDiv.setAttribute("id", "popup1");
//nodoDiv.addEventListener("click", function () { hideDiv(); }, false);
document.body.appendChild( nodoDiv );
var nodoDivPopup = document.createElement("DIV");
nodoDivPopup.setAttribute("id", "popup2");
nodoDivPopup.className = "popup";
var elem = document.getElementById("popup1");
divPopup = elem;
elem.appendChild( nodoDivPopup );
var nodoDivEsami= document.createElement("DIV");
nodoDivEsami.setAttribute("id", "contenitoreEsami");
nodoDivEsami.className = "content";
var elem = document.getElementById("popup2");
elem.appendChild( nodoDivEsami );
var nodoIFrame = document.createElement("IFRAME");
nodoIFrame.className = "content";
nodoIFrame.setAttribute("src", "esami_da_importare_TEST.html");
var nodoDivEsami = document.getElementById("contenitoreEsami");
nodoDivEsami.appendChild( nodoIFrame );
//window.alert( document.body.innerHTML );
}
_______file css
.overlayHidden{
visibility:hidden;
opacity:0;
}
the function hideDiv() is in the form, activated onClick on submit button.
the window.alert( ) in function hideDiv return "undefined"...
I think you're trying too hard, as iFrames are notoriously problematic. You don't need to use an iFrame, and you can predefine your DIVs in the HTML (unless you really need to create the DIV dynamically). For example:
<div id="popup1" class="overlayHidden">
<div id="contenitoreEsami" class-"content">
...
</div>
</div>
No code is needed for page load. When you want to display the pop-up, change its class to something that isn't hidden.

Change element text without jQuery?

I am trying to change the contents of a div without using jQuery. I want to select the div by id or class.
Ive managed to get append to work:
function appendHtml(targetC, htmldata) {
var theDiv = document.getElementById(targetC);
var newNode = document.createElement('div');
newNode.innerHTML = htmldata;
theDiv.appendChild(newNode)
}
But cant figure out how to change text of one..
Any ideas?
see this fiddle for a basic sample
<html>
<head>
<script>
function bold(targetC) {
var theDiv = document.getElementById(targetC);
theDiv.innerHTML = '<b>' + theDiv.innerHTML + '</b>';
}
</script>
</head>
<body onload='bold("message")'>
<div>Hello, World!</div>
<div id="message">What a nice day!</div>
</body>
</html>
Edited:
<div id="foo">old text</div>
The JS code:
function appendHtml(targetC, htmldata) {
var theDiv = document.getElementById(targetC);
theDiv.innerHTML = htmldata;
}
appendHtml('foo', 'new text');
Here is a fiddle: http://jsfiddle.net/7QjcB/
simply change the html of a div by using innerHTML
var anyDiv = document.getElementById(targetID);
html = "content";
anydiv.innerHTML(html);
as a variation of your provided function:
function changeHtml(targetC, htmldata) {
var theDiv = document.getElementById(targetC);
theDIV.innerHTML = htmldata;
}
Here is a fiddle that might answer your question. All I changed was getting the element before and then passing it in.
function appendHtml(targetC, htmldata) {
var newNode = document.createElement('div');
newNode.innerHTML = htmldata;
targetC.appendChild(newNode);
}
var getDiv = document.getElementById("testing");

Categories

Resources