JavaScript : How to add iframe after every paragraph? - javascript

I'm new to JavaScript and expect a answer from expert.
Suppose following is my piece of content -
<p> This is the first paragraph </p>
<p> This is the second paragraph </p>
and, I want to add few block of code after every paragraph and code became following -
<p> This is the first paragraph </p>
<figure class="x">
<iframe width="300" height="250" style="border:0; margin:0;" src="#">
</iframe>
</figure>
<p> This is the second paragraph </p>
<figure class="x">
<iframe width="300" height="250" style="border:0; margin:0;" src="#">
</iframe>
</figure>

You can try this javascript to get started.
// get all "p" tags
var elements = document.getElementsByTagName('p');
for (var i = 0; i < elements.length; i++) {
// create figure
const figure = document.createElement("figure");
figure.className = "x";
// create iframe
const iframe = document.createElement("iframe");
iframe.setAttribute("width", "300");
iframe.setAttribute("height", "250");
iframe.setAttribute("href", "#");
iframe.style.border = 0;
iframe.style.margin = 0;
figure.appendChild(iframe);
// append to "p" tag
elements[i].parentNode.insertBefore(figure, elements[i].nextSibling);
}​

You need to create figure HTML element that has a child iframe and then add the figure element after every p
How to insert an element after another element in JavaScript without using a library?
const paras = document.querySelectorAll("p");
function createIframe(width, height, style, src) {
const iframe = document.createElement("iframe");
iframe.setAttribute("width", width);
iframe.setAttribute("height", height);
iframe.setAttribute("style", style);
iframe.setAttribute("src", src);
return iframe;
}
function createFigureElement() {
const figure = document.createElement("figure");
figure.classList.add("x");
figure.appendChild(createIframe("300", "250", "border:0; margin:0;", "#"));
return figure;
}
function insertAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
paras.forEach((p) => {
insertAfter(p, createFigureElement());
});
<p> This is the first paragraph </p>
<p> This is the second paragraph </p>

Probably the shortest way:
document.querySelectorAll('p').forEach(p => {
p.insertAdjacentHTML('afterEnd',
`<figure class="x">
<iframe width="300" height="250" style="border:0; margin:0;" src="#"></iframe>
</figure>`
);
})
<p> This is the first paragraph </p>
<p> This is the second paragraph </p>

Related

Adding Div With IFrame Through JavaScript

I need to newProductPanelContainer insie replaceclass="Replace" through JS. I'm wondering why this doesn't add anything? I'm adding an iframe to it.
Where to add
<div class="Replace">
<div class="hello">Hello</div>
<div class="hi">Hi</div>
<div class="yes">Wait</div>
</div>
Expected Output
<div class="Replace">
<div class="hello">Hello</div>
<div class="hi">Hi</div>
<div class="yes">Wait</div>
<div class="newProductPanelContainer">
<iframe id="productPanelIFrame" src="https://test.com" width="100%" height="100%" style="border: none"></iframe>
</div>
</div>
Iframe div
<script type="text/javascript">
var innerDiv = document.createElement("div");
innerDiv.className = 'newProductPanelContainer';
innerDiv.innerHTML = `<iframe id="productPanelIFrame" src="https://test.com" width="100%" height="100%" style="border: none"></iframe>`;
innerDiv.style.width = "100%";
var hello = document.getElementsByClassName("Replace");
hello.appendChild(innerDiv);
</script>
getElementsByClassName returns a collection. You can iterate over the collection and add the iframe to each element in the collection or select an (probably the first) element and add the iframe to that.
Alternatively use the querySelector method which returns the first matching element in the DOM. This is what I have done below. Note don't get confused with querySelectorAll, which returns a collection.
var innerDiv = document.createElement("div");
innerDiv.className = 'newProductPanelContainer';
innerDiv.innerHTML = `<p>I'm inserted</p><iframe id="productPanelIFrame" src="https://test.com" width="100%" height="100%" style="border: none"></iframe>`;
innerDiv.style.width = "100%";
var hello = document.querySelector(".Replace");
hello.appendChild(innerDiv);
<div class="Replace">
<div class="hello">Hello</div>
<div class="hi">Hi</div>
<div class="yes">Wait</div>
</div>
#1: You can not create an element with specific class name newProductPanelContainer with just document.createElement("newProductPanelContainer")
you can use the 2nd parameter to do that (the options) refer this
#2: You can not get the DOM of un-mount element const productPanelIFrame = document.getElementById("productPanelIFrame");
the Iframe.productPanelIFrame is the children of div.newProductPanelContainer. But you can see, its parent has not mounted yet.
Try this. It works for me
const innerDiv = document.createElement("div");
innerDiv.className = "newProductPanelContainer";
innerDiv.style.width = "100%";
const iFR = document.createElement("iframe");
iFR.id = "productPanelIFrame";
iFR.src = "https://test.com";
iFR.width = "100%";
iFR.height = "100%";
iFR.style = "border: none";
const hello = document.getElementsByClassName("Replace");
hello[0].appendChild(innerDiv);
innerDiv.appendChild(iFR);

Can’t set figcaption text as firstChild of figure

I can set the text of a figcaption if I access it by its ID (Line commented out in code below). However I can’t set it if I access the figcaption as firstChild of the figure. Why not?
<body>
<figure id="fig1">
<figcaption id="figcap1">Camberley Mail</figcaption>
<button type="button" id="thumb1" onclick="showBigImg (1);"></button>
<p>Text to go with picture.</p>
</figure>
<script>
"use strict";
function showBigImg(figNum) {
// let temp = document.getElementById("figcap" + figNum);
let temp = document.getElementById("fig" + figNum).firstChild;
temp.innerHTML = "some text";
}
</script>
</body>
</html>

Insert a new h3 element before the first paragraph in the body using javascript

I want to insert a new h3 element having my name before the first paragraph in the HTML only by using javascript. I do not want to edit the HTML file or the CSS file for it.
I have tried this code in the javascript file
let h3e = document.createElement("h3");
h3e.textContent("Student Name");
document.body.insertBefore(h3e, document.body.firstChild);
But it is not working
let h3e = document.createElement("h3");
h3e.textContent("Student Name");
document.body.insertBefore(h3e, document.body.firstChild);
<body>
<header>
<h1>Bumblebee</h1>
</header>
<main>
<h2>General description</h2>
<figure><img src="bee1.jpg" />
<figcaption>A common bumblebee extending its tongue towards a Heuchera inflorescence.
</figcaption>
</figure>
<p>Bumblebees vary in o about 40 mm longginger beast".</p>
<h2>Distribution and habitat</h2>
<p>Test data</p>
</body>
To insert after the paragraph you need to call the insertBefore method on the immediate parent Node of the paragraph Node. So its not document you want to call it on but the main element. Note: in your example the main tag isn't closed. If you took away the main Node then you could use document.insertBefore as then document is the immediate parent of the paragraph.
So to do it with your above example, you could do it as shown below. I put in a time delay to show it before and after the element is inserted.
<html>
<body>
<header>
<h1>Bumblebee</h1>
</header>
<main>
<h2>General description</h2>
<figure><img src="https://upload.wikimedia.org/wikipedia/en/thumb/a/a8/Xylocopa_bee1.jpg/300px-Xylocopa_bee1.jpg" />
<figcaption>A common bumblebee extending its tongue towards a Heuchera inflorescence.
</figcaption>
</figure>
<p>Bumblebees vary in o about 40 mm longginger beast".</p>
<h2>Distribution and habitat</h2>
</main>
<p>Test data</p>
</body>
<script>
setTimeout(() => {
const h3e = document.createElement("h3");
h3e.textContent ="Student Name";
const mainElem = document.querySelector('main');
const paragraph = mainElem.querySelector("p");
mainElem.insertBefore(h3e, paragraph);
}, 1000);
</script>
</html>
You may want to look to the other answer wrt best practice for setting the text in the h3 node.
Another way to do it that is perhaps more robust is to call insertBefore on the parent of the paragraph node.
e.g.
paragraph.parentNode.insertBefore(h3e, paragraph);
Just Simply Do like that
let p = document.getElementsByTagName('p')[0]
p.outerHTML = '<h3>Student Name</h3>' + p.outerHTML
Your problem is here
h3e.textContent("Student Name");
// Error msg: "Uncaught TypeError: h3e.textContent is not a function",
Change to
var t = document.createTextNode("Student Name");
h3e.appendChild(t);
Or as #Paul Rooney's comment:
h3e.textContent ="Student Name";
Full code & demo here:
var h3e = document.createElement("H3");
var t = document.createTextNode("Student Name");
h3e.appendChild(t);
document.body.insertBefore(h3e, document.body.firstChild);
<body>
<header>
<h1>Bumblebee</h1>
</header>
<main>
<h2>General description</h2>
<figure><img src="bee1.jpg" />
<figcaption>A common bumblebee extending its tongue towards a Heuchera inflorescence.
</figcaption>
</figure>
<p>Bumblebees vary in o about 40 mm longginger beast".</p>
<h2>Distribution and habitat</h2>
<p>Test data</p>
</body>
Read this thread in more detail: TextNode or textContent?

Javascript replace parent html (remove child)

I would like loop each iframes tags I've on my page and replace them all with a new div and on the way delete also the parent content so the new div will be the only child:
<div id="parent">
<p>this is parent content</p>
<iframe src="http://www.example.com" id="iframe10"></iframe>
</div>
Result should be:
<div id="parent">
<div id="newdiv">this is new div</div>
</div>
Here is my code for looping all iframes on page, the problem I don't understand how I can access each iframe parent and delete its contents:
var i, frames;
frames = document.getElementsByTagName("iframe");
for (i = 0; i < frames.length; ++i)
{
frame_id = frames[i].id;
}
Thanks
Shai
you can write it as following:
function remove_frames() {
var i = 0;
var frames = document.getElementsByTagName("iframe");
while (frames.length > 0) {
var f = frames[0];
var p = f.parentElement;
if (p) {
while (p.children.length > 0) {
p.children[0].remove();
}
p.innerHTML = "<div id=\"newdiv" + i + "\">this is new div" + i + "</div>";
i++; //increase id index
//p.appendChild(
}
}
}
<p><input type="button" value="Execute" onclick="remove_frames()" /></p>
<div id="parent">
<p>this is parent content</p>
<iframe src="http://www.example.com" id="iframe10"></iframe>
</div>
<p style="color:#6595ee">This element does not contain any sibling IFrame and must be exist in final result!</p>
<div id="parent2">
<p>this is parent2 content...</p>
<div>another element</div>
<iframe src="http://www.example.com" id="iframe20"></iframe>
<p>another element after iframe.</p>
</div>
var i, frames;
frames = document.getElementsByTagName("iframe");
for (i = frames.length; i; --i) // the array-like object shrinks every time a frame is removed so we have to loop backwards
{
//frame_id = frames[i].id;
// get the parent element
var parent = frames[i].parentElement;
// empty it (remove all it's elements)
while(parent.firstChild)
parent.removeChild(parent.firstChild);
// add the new div
var div = /* create new div */;
parent.appendChild(div);
}
You could use the parentElement
var iframes = document.getElementsByTagName("iframe");
iframes[0].parentElement.innerHTML = `<div id="newdiv">this is new div</div>`;
<div id="parent">
<p>this is parent content</p>
<iframe src="http://www.example.com" id="iframe10"></iframe>
</div>
You can use Node.parentNode to get the parent and Node.removeChild or Element.innerHTML to delete the content.
var i, frames;
frames = document.getElementsByTagName("iframe");
for (i = frames.length-1; i >=0; i--) {
var frame = frames[i];
if (frame.parentNode) {
var parent = frame.parentNode;
while (parent.firstChild) {
parent.removeChild(parent.firstChild);
}
}
}
<div id="parent">
<p>this is parent content</p>
<iframe src="http://www.example.com" id="iframe10"></iframe>
</div>

Image not appending in Javascript

I am new to javascript, I am trying to append a img tag inside a div tag.
but it is not concatinating with already existing elements inside the div.
This is my HTML code:
<div class="ce_label">
<span>some text</span>
<span>some text</span>
</div>
My javascript Code :
var sel = '.ce_label';
var toolTemplate = [
'<img src="smiley.gif" alt="Smiley face" height="42" width="42">'
];
window.onload = function() {
var x = document.querySelectorAll(sel);
var commentHtml = toolTemplate.join('');
for (var i = 0; i < x.length; i++) {
x[i].appendChild = commentHtml;
}
};
So my output should be :
<div class="ce_label">
<img src="smiley.gif" alt="Smiley face" height="42" width="42">
<span>some text</span>
<span>some text</span>
</div>
But I could not get this output..
Can anyone help me to fix it???
Thanks in advance.
This line
x[i].appendChild = commentHtml;
tries to assign a string to the element's appendChild property, which refers to a function you can't overwrite.
If you want to replace the element's content with that HTML, assign to innerHTML:
x[i].innerHTML = commentHtml;
If you want to append to the element's curent contents, call the element's insertAdjacentHTML method:
x[i].insertAdjacentHTML("beforeend", commentHtml);

Categories

Resources