I have two pages on the same domain. Home.html and page2.html are their names.
home.html has the following content
<html>
<iframe id="one" src="page2.html" style="display:none"></iframe>
<div id="container">
<h1>Title of Page</h1>
<div id="ShowHere"></div>
</div>
</html>
page2.html has the following content.
<html>
<div id="container">
<span id="target">Some Text</span>
</div>
<span>Don't Show This Text</span>
</html>
I would like to use some javascript to get the contents of "target" from within the iframe with Id="one" on the page home.html and then change the innerhtml of the element id=ShowHere to show the html within the element "target" such that, it shows the words "Some Text" under the word "Title of Page".
I think that the following is a start, put at the bottom of home.html:
<script>
var frameSource = document.getElementById("one").contentWindow.document.documentElement.outerHTML;
// ANSWER TO MY QUESTION
document.getElementById("ShowHere").innerHTML = frameSource;
</script>
I've searched around and seen a few answers that supposedly do this, but none which provide a meaningful explanation of HOW to do this, and none which I can get to work. I'd prefer to use plain vanilla javascript, but Jquery is alright too.
Based on what I am trying to do, which is get the content (i.e. innerhtml) of a div from another page on the same domain, I wonder if there is a better approach than creating an invisible iframe and then reading it. Answers which achieve the desired result, but through another mechanism are also welcome.
Using the answer for this question
So, firstly you have to find the iframe:
var iframe = document.getElementById('one');
Then you should get the iframe contents:
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
And now you can use getElementById to find DOM-elements in the iframe:
var iframeContent;
if (iframeDocument) {
iframeContent = iframeDocument.getElementById('target').innerHTML;
}
Now in the iframeContent you have the contents of span you need to show on the main page, so you can just find element where you want to display iframeContent and set the innerHTML property:
var divToShow = document.getElementById('ShowHere');
divToShow.innerHTML = iframeContent;
And that's all.
I hope my answer will help you to solve your problem.
Thanks : )
You can use selectors (like getElementById, etc) in iframes similar to those found in your normal window via iframe.contentWindow.document.
So if you wanted to get the contents of target on the second page, you can get it via document.getElementById("one").contentWindow.document.getElementById("target")
Edit:
You also probably should wait until the iframe is loaded before trying to read elements from it. So altogether:
var init = function(){
var frameDocument = document.getElementById("one").contentWindow.document;
document.getElementById("ShowHere").innerHTML = frameDocument.getElementById("target").innerHTML;
};
if(document.getElementById("one").contentWindow.document.getElementById("target")) { // iframe is loaded
init();
} else {
document.getElementById("one").contentWindow.onload = init;
}
Related
So i'm working on a chat application and i want to add smileys. So i used two html pages. the first one contain the text area when we wright the messages and an iframe that references the second html page.
<div class="col-12">
<textarea class="col-12 row-12 var_MessageInput" id="textmsg" placeholder="Write a reply..."></textarea>
</div>
in the second html page i have smiley images
<img src="../../../images/sad_smile.gif" onclick="insertSmiley('sad');"/>
<img src="../../../images/angel_smile.gif" onclick="insertSmiley('angel');"/>
<img src="../../../images/happy_smile.gif" onclick="insetSmiley('happy');" />
So i want that when i click at a smiley image that a text got inserted in my text area so i used the following script
function insertSmiley(smiley) {
var currentText = document.getElementById("textmsg");
var smileyWithPadding = " " + smiley + " ";
currentText.value += smileyWithPadding;
currentText.focus();
}
But it doens't work :( i thought the problem might be in document.getElementById since it's another html page but i have no idea how to solve it.
Thanks a lot
Have you included the <script src="Scripts_Chatapp/emoticone.js"></script> in iframe too? If yes, remove the script reference from iFrame.
Move the script reference <script src="Scripts_Chatapp/emoticone.js"></script> at top of page with other script tags.
Change the onclick="insertSmiley('sad');" TO onclick="parent.insertSmiley('sad');".
This will call the parent function and make changes on that page, since element exists on parent.
You have one typo in onclick="insetSmiley('happy');" it should be onclick="insertSmiley('happy');". I checked it and it works for me.
In your JS code, use:
window.location = "second_HTML_Page.html" ;
The problem is that when the function is triggered within the iFrame, the scopes become complicated.
A solution would be to make the function global by defining it at the window level. And then when the function is to be triggered inside the iFrame, it can call the function of the iFrame's parent (the main window).
Example Fiddle: http://jsfiddle.net/e37rrtb1/2/
Hello my question is how to write inside script called parent element with document.write when parent element is unknown
You may consider this as advertising script
For example:
<div>
<script src="http://www.pokemonpets.com/scripts/ads_simple.js"></script>
</div>
My script code below but not working right now
document.write('<a title="Bedava Pokemon Online Oyunu" target="_blank" href="http://www.pokemonpets.com/Register"><img src="http://orig04.deviantart.net/58d0/f/2015/213/8/4/pokemonpets_by_monstermmorpg-d93plr1.png" /></a>');
So somehow i have to make it work without knowing parent element or without knowing whether page has JQuery or not.
How does advertising companies handle this?
You don't want to use document.write, you want to find your script tag and replace it with your new content. You can do that by looking for a script tag with your URL, then having it's parent replace it.
scripts = document.getElementsByTagName("script");
for(var i in scripts){
if(scripts[i].src.indexOf('//www.pokemonpets.com/scripts/ads_simple.js') !== -1){
var wrapper = document.createElement('div');
wrapper.innerHTML = '<a title="Bedava Pokemon Online Oyunu" target="_blank" href="http://www.pokemonpets.com/Register"><img src="http://orig04.deviantart.net/58d0/f/2015/213/8/4/pokemonpets_by_monstermmorpg-d93plr1.png" /></a>';
scripts[i].parentElement.replaceChild(wrapper,scripts[i]);
}
}
This is totally untested, not even for syntax, so you might need to fiddle with it a bit.
This is going to be hard to explain but I will do my best. I want to write a Javascript function that takes two parameters (title, content) and creates a <div> tag in the <body> tag. The <div> tag should look like this.
<div>
<h2>title</h2>
<p>content</p>
</div>
My javascript code looks like this:
function addElement (title, content) {
var newDiv = document.createElement("div");
var newH2 = document.createElement("h2");
var title = document.createTextNode(header);
newH2.appendChild(title);
var p = document.createElement("p");
var post = document.createTextNode(entry);
p.appendChild(post);
newDiv.appendChild(newH2);
newDiv.appendChild(p);
// Missing codes here...
}
I dont know how to finish my method. Because of I have almost hundreds of tags inside my page and I want this new tags (when a user makes a new input) will appear on same place somewhere in the middle of the html code page in order to keep things organized.
If you would like to use jQuery take a look at this fiddle: http://jsfiddle.net/panpymq2/
In my fiddle I am binding to a button press. Then I call a method that appends new generated html to the body of the page. You can enter change where you are appending the new HTML with CSS3 selectors. just modify the $("insert selector there").append...
UPDATE
As per the new requirements I have updated my fiddle: http://jsfiddle.net/panpymq2/1/
I now prepend the new html to the document.
You already know how to add elements as children of other elements. That's what you used to add the h2 and p to the div. You could use the same appendChild to add the div to the document:
document.body.appendChild(newDiv);
But you don't want it at the bottom of the page--you want it "in the middle of the html code page". One straightforward way to do this is to add the newDiv to a container that's in the right place, in the middle of the page.
You'd first create this container in the page HTML:
<!doctype html>
<body>
<p>stuff before</p>
<div id="container"></div>
<p>stuff after</p>
</body>
Then, finish off addElement with:
document.getElementById('container').appendChild(newDiv);
One way would be if addElement took a third parameter which is the sibling/parent you want to insert your new element next to/within.
function addElement(title, content, target) {
...
target.insertAdjacentElement('afterend', newDiv);
// or
target.appendChild(newDiv);
}
I think this is as much of an HTML as a CSS problem. I've had the same issue.
One way of solving this problem is to make an (extra) container <div> as follows:
<div id="outer_container_elems">
<div id="inner_container_elems">
...
</div>
</div>
And append to inner_container_elems
Hope this helps!
So I'm trying to grab some attributes of a div table from the DOM from within a script - and failing.
Code should speak for itself:
<head>
<script type = "text/javascript" src = "SCRIPT_IN_QUESTION.js"></script>
</head>
<body>
<div id = "my_elements">
<!-- I want to access 'attribute-one' data attributes from
all children -->
<div data-attribute-one = "Hello"></div>
<div data-attribute-one = "World"></div>
</div>
</body>
I've seen how this is done with an embedded script in the DOM using something along the lines of:
<script type = "text/javascript">
var values = document.getElementById('my_elements').childNodes;
var foo = values[0].getAttribute('data-attribute-one');
</script>
I'm trying to access these attributes from within a script that isn't embedded into the DOM, and getAttribute is undefined - guess you can only ue that within the DOM.
How do I access this data in a script 'outside' the DOM?
As the below comment states, doing this after the DOM has been loaded makes sense to do, and I'm doing it something like:
window.addEventListener('load', onload, false);
function onload(){
var data = document.getElementById('canvas_segments').childNodes;
//This throws an undefined error
var attribute = data[0].getAttribute('data-attribute-one');
}
Many thanks
Use .children instead of .childNodes (which also includes text nodes). And you may need to wrap your call into onload event, e.g.
<body onload="onLoad()";>
<div id = "my_elements">
<!-- I want to access 'attribute-one' data attributes from
all children -->
<div data-attribute-one = "Hello"></div>
<div data-attribute-one = "World"></div>
</div>
</body>
and in your script:
function onLoad() {
var values = document.getElementById('my_elements').children;
var foo = values[0].getAttribute('data-attribute-one');
}
You have a timing issue here. The script in question is being executed before the DOM is complete, so there is no element.
Either you can move the script tag to the bottom of the page, after all other markup, or you can put the code in a window.onload function.
First of all in the code snippet above, you are attaching the javascript before the DOM structure is loaded. Attach the js file after body so that the HTML content gets loaded first and then the js executes.
After you have done this you will still hit an issue saying, 'Uncaught TypeError: undefined is not a function.' This will be because you are using 'ChildNodes' instead of 'Children.' The difference between the two is that Children gets only Elements whereas 'ChildNodes' will fetch nodes too. Refer this question for a clearer distinction between the two (What is the difference between children and childNodes in JavaScript?)
You might be interested in a working copy of your code: http://goo.gl/HonxtJ
The html is like this
<iframe id="MainFrame">
<div id="Maintest">This is main text
<div id ="SecondTest">This is second layer
<div id="ThirdTest">This is third layer</div>
</div>
</div>
</iframe>
The javascript to access elements in frame is like this
var iframe = document.getElementById('MainFrame');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
console.log(iframe);
var mydiv = innerDoc.getElementById("Maintest");
console.log(mydiv);
var seconddiv = innerDoc.getElementById("SecondTest");
var thirddiv = innerDoc.getElementById("ThirdTest");
console.log(seconddiv+thirddiv);
mydiv, seconddiv as well as thirddiv give null.I have seen on many posts that this is the way to access iframe element.I dont know why its giving null.Help appreciated.
Thanks
Swaraj
Your implementation for using an iframe is incorrect, I believe. Any content within <iframe> tags is what would be displayed for a browser that does not support iframes. There are only two ways to insert content into an iframe that I'm aware of:
<iframe src="/example/content.html">Your browser doesn't support iframes.</iframe>
and using javascript to append child nodes to the iframe using your innerDoc reference, such as:
innerDoc.body.appendChild(child_ref);
UPDATE:
Just to be clear, the html content you want to reference within your iframe needs to be in a separate file, such as my_content.html and the iframe needs to reference that file in the "src=" field, like: <iframe src="my_content.html">.