inserting divs into the dom using javascript? - javascript

im trying to insert a new div into the DOM with an id of "app"
var new_div = document.createElement("div");
var app_div = document.getElementById("app");
document.body.insertBefore(new_div, app_div);​
this gives me an error in the console:
Uncaught TypeError: Cannot call method 'insertBefore' of null
but i don't know why?

You need to wrap your code to window.onload handler:
window.onload = function() {
var new_div = document.createElement("div");
var app_div = document.getElementById("app");
document.body.insertBefore(new_div, app_div);
}
Example on jsFiddle.

Except that it would be better wrapped in onload() as suggested by Igor, don't you want to add new_div to the document first?
document.body.insertBefore(new_div, document.body.firstChild);

Try use jquery document.ready event

Related

addEventListener without handler

I want to set an Event on an Element without inline Events like:
let myDiv = document.querySelector("#div");
myDiv.addEventListener("click",function({this.style.opacity = "0";})
<div onclick="zero()"></div>
this is code:
<div id="div"></div>
I expected the opacity of div Element changes to 0 but in console of the browser show this error:
Uncaught error: cannot read property addEventListener of null!
You're missing some brackets and introducing an unnecessary line break:
let myDiv = document.querySelector("#div");
myDiv.addEventListener("click", function() {
this.style.opacity = "0";
});
<div id="div">Hallo</div>
With regard to the error you're getting it suggests that you haven't allowed the DOM to load - ie you're trying to add an event listener to an element that isn't there. Your code is in the right order in your question but it's something to be mindful of.
Please try to check the syntax you have written
let myDiv = document.querySelector("#div");
myDiv.addEventListener("click", function() {
this.style.opacity = "0";
});
<div id="div">Content</div>

How to get id of element in an iframe?

I have an <iframe> with a local file embedded. I don't know how to get a specific element in this document.
I have tried window.top.document.getElementById('numPages') and $("#myiframe").contents().find("#numPages") to get element with an id of numPages.
Try using .contentDocument
eg:
var iframe = document.getElementById("myFrame"),
idocument = iframe.contentDocument
// Use idocument instead of document
To get the element in plain javascript try using contentWindow
document.getElementById('myiframe').contentWindow.document.body.getElementById('numPages');
By this way, You can get frame id and set css property inside frame element. It'll work 100%.
<script>
window.onload = function WindowLoad(event) {
let iframe = document.getElementsByTagName("iframe")[0];
var iframevar = document.getElementById(iframe.id);
var elmnt = iframevar.contentWindow.document.getElementById("header_27");
elmnt.style.color = 'black';
var elmnt = iframevar.contentWindow.document.getElementById("header_59");
elmnt.style.color = 'black';
}
</script>

Jquery appending to div

i am trying to append to a div with an ID that is dynamic
<script>
var GameId = "{{$match['gameId']}}";
var Ts = '{{$match['createDate']}}';
var TsInt = parseInt(Ts);
var timeSinceGame = moment(TsInt).fromNow();
$('#'+GameId).append(timeSinceGame );
</script>
the script is run inside of a php foreach loop.
the div ID is set the same as GameID variable
however nothing is appended to anything when run what's wrong here?
None of your jQuery is wrapped in DOM ready events, so the elements are likely not in the DOM yet when the code runs.
Try adding a DOM ready wrapper:
<script>
$(function(){
var GameId = "{{$match['gameId']}}";
var Ts = '{{$match['createDate']}}';
var TsInt = parseInt(Ts);
var timeSinceGame = moment(TsInt).fromNow();
$('#'+GameId).append(timeSinceGame );
});
</script>
$(function(){ is just a handy shortcut for $(document).ready(function(){
The alternative is to simply inject your code after the elements in the page, so that they do already exist.

Get the text from an external HTML document

My goal is to get the text from a HTML document which does not call any functions from my .jsp file.
I've looked around and I thought I had found the answer to my problem but it doesn't seem to be working, and other answers consist of using jQuery (which I am both unfamiliar with and not allowed to use).
This is my code so far:
function getText(divID) {
var w = window.open("test.html");
var body = w.document.body;
var div = document.getElementById(divID);
var textContent = body.textContent || body.innerText;
console.log(textContent);
//div.appendChild(document.createTextNode(textContent));
}
So as you can see, I'm trying to get the body of one HTML document and have it appear in another. Am I on the right tracks?
EDIT: Ok so I seem to have made my problem quite confusing. I call the function in a HTML document called html.html, but I want to get the text from test.html, then have it appear in html.html. It has to be like this because I can't assume that the HTML document I want to read from will include my .jsp file in its head.
At the moment I am getting the following error.
Uncaught TypeError: Cannot read property 'body' of undefined
The reason document.body in the other window is undefined, is because the other window has not loaded and rendered the document yet.
One solution would be to wait for the onload event.
function getText(divID) {
var w = window.open("test.html");
w.addEventListener("load", function() {
var body = w.document.body;
var div = document.getElementById(divID);
var textContent = body.textContent || body.innerText;
console.log(textContent);
});
}
Make sure you run the getText function on a user event like a click, else window.open will fail.
If all you want to do is get the contents of the other window, using AJAX would probably be a better option.
function getText(divID) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 ) {
var body = xhr.response.body;
var div = document.getElementById(divID);
var textContent = body.textContent || body.innerText;
console.log(textContent);
}
};
xhr.open("GET", "test.html", true);
xhr.responseType = "document";
xhr.send();
}

Target child of children with .each() in jQuery

I’m iterating through the elements and grabbing the src attribute of the child of that element. I have this HTML code:
<noscript data-alt="super awesome">
<img src="http://farm9.staticflickr.com/8235/8585847956_39864361e3.jpg" alt="something" />
</noscript>
<noscript data-alt="super awesome">
<img src="http://farm9.staticflickr.com/8235/8585847956_39864361e3.jpg" alt="something" />
</noscript>
and jQuery:
$('body').children().each(function() {
var noscriptTag = $(this)[0];
var imgAlt = noscriptTag.getAttribute("data-alt");
var img_src = noscriptTag.find('img');
var img_regular = img_src.getAttribute("src");
console.log(img_regular);
});
But I’m getting this error:
Uncaught TypeError: Object #<HTMLElement> has no method 'find'
I also tried various other combinations (like $(this).find('img');) without making it work.
Here’s the demo: http://jsfiddle.net/LjWhw/
How do I target the img tag of that element? Thanks!
UPDATE: You can’t target elements which are inside <noscript> with JavaScript.
You are trying to call find jQuery function on DOM object, Use jQuery object instead of DOM javascript object to call find on it.
Change
var noscriptTag = $(this)[0];
To
var noscriptTag = $(this);
Edit: You will also need to change the code accordingly e.g. img_src.getAttribute("src"); to img_src[0].getAttribute("src"); or img_src.attr("src");
I would suggest you to do it this way:
$('body').children().each(function() {
var noscriptTag = $(this).find('noscript').first();
//---------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-----this way
var imgAlt = noscriptTag.getAttribute("data-alt");
var img_src = noscriptTag.find('img');
var img_regular = img_src.attr("src");
console.log(img_regular);
});
try this
http://jsfiddle.net/UQJsy/1/
$('noscript').each(function () {
var noscriptTag = $(this);
var imgAlt = noscriptTag.attr("data-alt");
var img_src = noscriptTag.children('img');
var img_regular = img_src.attr("src");
alert(imgAlt);
});

Categories

Resources