Writing HTML to new window opened issue - javascript

I have this code:
<div class="col3">
<a id = "training-launch-button" href="javascript:void(0);" title=" My title here" class="button" onClick="Test();">Launch</a>
</div>
function Test() {
var new_window= window.open('','Ratting','width=550,height=170,0,status=0,resizable=1');
new_window.document.createElement("div");
document.getElementsByTagName('div')[0].innerHTML = '<ol><li>html data</li></ol>';
}
something is not right, I dont see the ordered list item?
I eventually want to build some HTML in the new window.

Use this Js
function Test() {
var newWindow= window.open('','Ratting','width=550,height=170,0,status=0,resizable=1');
var newContent = "<HTML><HEAD><TITLE>One Sub Window</TITLE></HEAD>";
newContent += "<BODY><div><ol><li>html data</li></ol></div>";
newContent += "</BODY></HTML>";
newWindow.document.write(newContent);
newWindow.document.close();
}

I think this is your problem; getElementsByName returns an array, not one element, so;
new_window.document.getElementsByTagName('div')[0].innerHTML = '<ol><li>html data</li></ol>';
NB: I have a '[0]' in there

I would try
new_window.document.getElementsByTagName('div')[0].innerHTML = ...

This should do it:
var new_window= window.open('','Ratting','width=550,height=170,0,status=0,resizable=1');
var div = new_window.document.createElement('div');
new_window.document.body.appendChild(div);
div.innerHTML = '<ol><li>html data</li></ol>';

You are actually not appending the new div to the new document's body, you'll have to use .appendChild() method for that, see this :
function Test() {
var new_window = window.open('','Ratting','width=550,height=170,0,status=0,resizable=1');
var div = new_window.document.createElement("div");
new_window.document.getElementsByTagName('body')[0].appendChild(div);
div.innerHTML = '<ol><li>html data</li></ol>';
}
see here - working example

Related

Replacing text with new text when button click

I have 3 data in the JSON file and want each data to be displayed 1 by 1 at a single click.The problem is the previous data was'nt replaced by the new data as the button was click. They ended up being side by side (image below). How do i overcome this? Thanks in advance.
JSON FILE
[
{"quote": "Everyday Is A New Day"},
{"quote": "Trust Your Guts"},
{"quote": "All The Best"}
]
HTML
<p id="text"></p>
<button id="btn">GENERATE</button>
JAVASCRIPT
var text = document.getElementById("text");
var btn = document.getElementById("btn");
var i=0;
btn.addEventListener("click", function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'data2.json');
ourRequest.onload = renderHTML;
ourRequest.send();
});
function renderHTML(data) {
var htmlString =data[i].quote;
i++;
text.insertAdjacentHTML('beforeend', htmlString);
};
instead of
text.insertAdjacentHTML('beforeend', htmlString);
just use
text.innerHTML = htmlString;
insertAdjacentHTML doesn't replace the html.
Instead of using insertAdjacentHTML, set innerHTML directly. So your new function would look like:
function renderHTML(data) {
var htmlString =data[i].quote;
i++;
i %= data.length; // new
text.innerHTML = htmlString; // changed
}
I also inserted the line i %= data.length; so you don't go off the end of the array, and instead loop around to the beginning of data.

trying to dynamically replace the url from "a href" but javascript is not updating results

I'm trying to replace the urls in the html using javascript but it is not working although when I test it by I "alerting" them the values pop up correctly, but when I publish it and click on the images the new urls are not applied. Any help would be greatly appreciated
Could you please look at the code and tell me what is going on?:
<script>
var rutaBase = "assets/fotos/";
function cambieFotos(cualFoto) {
var listaFotos = ["360.jpg", "foto3.jpg", "mathura.jpg"];
var numFotosLista = listaFotos.length;
var foto1 = document.getElementById("foto1");
var foto2 = document.getElementById("foto2");
var foto3 = document.getElementById("foto3");
for (i = 0; i < 3; i++) {
var fotoAleatoria = listaFotos[Math.floor(Math.random() * numFotosLista)];
var fotoRoll = document.getElementById("foto" + (i + 1));
fotoRoll.src = "assets/fotos/" + fotoAleatoria;
fotoRoll.href = "assets/fotos/" + fotoAleatoria; //this code is not working.
var sacarFotoLista = listaFotos.indexOf(fotoAleatoria);
listaFotos.splice(sacarFotoLista, 1);
numFotosLista = listaFotos.length;
}
}
</script>
<div id="contenedor">
<img id="foto1" onMouseOver="cambieFotos(this)" src="assets/fotos/360.jpg"> <--!this needs to update-->
<img id="foto2" onMouseOver="cambieFotos(this)" src="assets/fotos/foto3.JPG"><--!this needs to update-->
<img id="foto3" onMouseOver="cambieFotos(this)" src="assets/fotos/mathura.jpg"><--!this needs to update-->
</div>
<!--contenedor-->
fotoRoll is an <img>, not the surrounding <a>. You should modify the parent instead:
fotoRoll.parentNode.href="assets/fotos/"+fotoAleatoria;
You're setting the href on the image element, not the hyperlink element. Try something like
fotoRoll.parentNode.href="assets/fotos/"+fotoAleatoria;

First javascript function/link stops working?

Im fairly new to javascript and i'm trying to do a simple function where my div can be changed with a click of a link. Everything works fine except for when I click on my first link again, it stops working. The others continue to work...
Here is my code...hope someone can help me! Thanks!
<script>
function changedivVIDEO(){
var div = document.getElementById("fw14video");
div.innerHTML = "<div id='main2'>Hello</div>";
}
function changedivCAMPAIGN(){
var div = document.getElementById("fw14campaign");
div.innerHTML = "<div id='main3'>Hello</div>";
}
function changedivRUNWAY(){
var div = document.getElementById("fw14campaign");
div.innerHTML = "<div id='main4'>Hello</div>";
}
</script>
<div id="main">
<div id="fw14video"></div>
<div id="fw14campaign"></div>
<div id="fw14runway"></div>
<div id="fw14runway"></div>
</div>
<p><h3>VIDEO</h3></p>
<p><h3>CAMPAIGN</h3></p>
<p><h3>RUNWAY</h3></p>
<p><h3>ACCESSORIES</h3></p>
</div>
I made an example that fills in the details I think are missing:
<div id="fw14video"></div>
<div id="fw14campaign"></div>
changediv1
changediv2
changediv3
<script>
function changediv1(e){
var div = document.getElementById("fw14video");
div.innerHTML = "<div id='main2'>div1</div>";
e.preventDefault();
}
function changediv2(e){
var div = document.getElementById("fw14campaign");
div.innerHTML = "<div id='main3'>div2</div>";
e.preventDefault();
}
function changediv3(e){
var div = document.getElementById("fw14campaign");
div.innerHTML = "<div id='main4'>div3</div>";
e.preventDefault();
}
</script>
This works as intended. I am using e.preventDefault() to make it not follow the links, and set text different so you can tell which got clicked. Some questions:
do you mean for the IDs to be different?
how did you bind your functions to the links? (I used onclick.)
I think this:
function changedivRUNWAY(){
var div = document.getElementById("fw14campaign");
div.innerHTML = "<div id='main4'>Hello</div>";
}
Should be:
function changedivRUNWAY(){
var div = document.getElementById("fw14runway");
div.innerHTML = "<div id='main4'>Hello</div>";
}
As a starter...and then if nothing else is missing in the code you posted there's a lose < /div> tag.

javascript extract html block from string

I have a string extracted from a div and stored in variable "str". I now need to extract the ... subset of it.
str = '<div id="xyz"><p>This is a paragraph</p><img src="http://bs.serving-sys.com/BurstingPipe/adServer.bs?cn=bsr&FlightID=2997227&Page=&PluID=0&Pos=9088" border=0 width=300 height=250></div>';
Thanks in advance for any help with this.
You could try something like the below:
var a = $(str).find('a').html();
make it innerHTML of a temporary div.
use getElementsByTagName("A") to retreive all "A" nodes.
get their HTML .
Here is a running example : http://jsfiddle.net/3fZch/
var str = '<div id="xyz"><p>This is a paragraph</p><img src="http://bs.serving-sys.com/BurstingPipe/adServer.bs?cn=bsr&FlightID=2997227&Page=&PluID=0&Pos=9088" border=0 width=300 height=250></div>';
var newElem = returnTheParentNode(str);
var anchors = newElem.getElementsByTagName('A');
/* anchors has all the a tags of the html string */
for(var i = 0 ; i < anchors.length ; i++)
{
var aHTML = getHTML(anchors[i]);
alert(aHTML);
}
function returnTheParentNode(htmlStr)
{
var myCont = document.createElement('DIV'); // create a div element
myCont.innerHTML = htmlStr; // create its children with the string
return myCont; // return the parent div
}
function getHTML(theNode)
{
var myCont = document.createElement('DIV');
myCont.insertBefore(theNode,null);
return myCont.innerHTML ;
}
The expression you need is:
str.match(/a href="([^"]*)"/)[1]
But this assumes there is only one a tag in your string and you used double quotes to delimit the href.
Made a jsfiddle: http://jsfiddle.net/eDAuv/
Why not extract the link BEFORE you store it in a string?
myLink = $(".myDiv a").html()
This could work:
var link = $(str).find("a").get(0).outerHTML;
alert(link);

How to get child element by ID in JavaScript?

I have following html:
<div id="note">
<textarea id="textid" class="textclass">Text</textarea>
</div>
How can I get textarea element? I can't use document.getElementById("textid") for it
I'm doing it like this now:
var note = document.getElementById("note");
var notetext = note.querySelector('#textid');
but it doesn't work in IE(8)
How else I can do it? jQuery is ok
Thanks
If jQuery is okay, you can use find(). It's basically equivalent to the way you are doing it right now.
$('#note').find('#textid');
You can also use jQuery selectors to basically achieve the same thing:
$('#note #textid');
Using these methods to get something that already has an ID is kind of strange, but I'm supplying these assuming it's not really how you plan on using it.
On a side note, you should know ID's should be unique in your webpage. If you plan on having multiple elements with the same "ID" consider using a specific class name.
Update 2020.03.10
It's a breeze to use native JS for this:
document.querySelector('#note #textid');
If you want to first find #note then #textid you have to check the first querySelector result. If it fails to match, chaining is no longer possible :(
var parent = document.querySelector('#note');
var child = parent ? parent.querySelector('#textid') : null;
Here is a pure JavaScript solution (without jQuery)
var _Utils = function ()
{
this.findChildById = function (element, childID, isSearchInnerDescendant) // isSearchInnerDescendant <= true for search in inner childern
{
var retElement = null;
var lstChildren = isSearchInnerDescendant ? Utils.getAllDescendant(element) : element.childNodes;
for (var i = 0; i < lstChildren.length; i++)
{
if (lstChildren[i].id == childID)
{
retElement = lstChildren[i];
break;
}
}
return retElement;
}
this.getAllDescendant = function (element, lstChildrenNodes)
{
lstChildrenNodes = lstChildrenNodes ? lstChildrenNodes : [];
var lstChildren = element.childNodes;
for (var i = 0; i < lstChildren.length; i++)
{
if (lstChildren[i].nodeType == 1) // 1 is 'ELEMENT_NODE'
{
lstChildrenNodes.push(lstChildren[i]);
lstChildrenNodes = Utils.getAllDescendant(lstChildren[i], lstChildrenNodes);
}
}
return lstChildrenNodes;
}
}
var Utils = new _Utils;
Example of use:
var myDiv = document.createElement("div");
myDiv.innerHTML = "<table id='tableToolbar'>" +
"<tr>" +
"<td>" +
"<div id='divIdToSearch'>" +
"</div>" +
"</td>" +
"</tr>" +
"</table>";
var divToSearch = Utils.findChildById(myDiv, "divIdToSearch", true);
(Dwell in atom)
<div id="note">
<textarea id="textid" class="textclass">Text</textarea>
</div>
<script type="text/javascript">
var note = document.getElementById('textid').value;
alert(note);
</script>
Using jQuery
$('#note textarea');
or just
$('#textid');
$(selectedDOM).find();
function looking for all dom objects inside the selected DOM.
i.e.
<div id="mainDiv">
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<div id="innerDiv">
link
<p>Paragraph 3</p>
</div>
</div>
here if you write;
$("#mainDiv").find("p");
you will get tree p elements together. On the other side,
$("#mainDiv").children("p");
Function searching in the just children DOMs of the selected DOM object. So, by this code you will get just paragraph 1 and paragraph 2. It is so beneficial to prevent browser doing unnecessary progress.

Categories

Resources