How i can insert an element in between in html using javascript? - javascript

I have to insert p tag in between other p tag in this example there only 3 p tag are there in my program there can be more so help me out.
**This is Html structure **
<div id="container">
<p>P1</p>
<p>p2</p>
<p>p3</p>
</div>
i want to insert a p tag in between using javascript . Thanks in advance.

You can insert elements through many different ways, but the most flexible is insertAdjacentHTML
and insertAdjacentElement
const secondP = document.querySelector("#container p:nth-child(2)");
const html = `<p>newly added p</p>`;
// add before the second p
secondP.insertAdjacentHTML("beforebegin", html);
// add after the second p
secondP.insertAdjacentHTML("afterend", html);
<div id="container">
<p>P1</p>
<p>p2</p>
<p>p3</p>
</div>

Based on your simplified question, a simpified answer:
const p = document.querySelector("#container p:nth-of-type(1)");
p.innerHTML += "<p>new p tag</P>";
Where as nth-of-type(1) selects the first p tag.
However, this question has been answered many times here, so please next time take some time to do some research.

I have a easy hack to do this in javscript:
document.getElementById("container").innerHTML += "<p>p4</p>";
However, you should be doing it by insertAdjacentElement
tempP = document.createElement('p');
tempP.innerText = "p4";
document.getElementById("container").insertAdjacentElement('afterend',tempP);

Related

add element/class to a first unique word from a string in javascript / jquery

I want to insert a tag from the first unique word from a string using javascript / jquery. It is something like:
jQuery(document).ready(function($){
$(".product_title:contains(NEW)").replace('NEW', '<span class="new">NEW</span>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
FROM: <h2 class="product_title">NEW Jeep Wrangler</h2>
INTO: <h2 class="product_title"><span class="new">NEW</span>Jeep Wrangler</h2>
FROM: <h2 class="product_title">REBUILT Jeep Wrangler</h2>
INTO: <h2 class="product_title"><span class="rebuilt">REBUILT</span>Jeep Wrangler</h2>
I tried below approach to replace the first word with html code but didn't work: I received a Uncaught TypeError: $(...).replace is not a function on console.
How to achieve this? I can't find any examples on the web that is applying this similar approach. Please advise.
UPDATE: I think I'm close, I use below approach:
$('.product_title').each(function() {
var text = $(this).text();
$(this).text(text.replace('NEW', '<span class="cust-woo-title-tag-new">NEW</span>'));
});
But the tags are displaying on the front end.
get all the product_title that contains "NEW"
store the previous html value (eg. NEW Jeep Wrangler)
remove the "NEW" word (NEW Jeep Wrangler becomes Jeep Wrangler)
update the innerHTML
$(document).ready(function($){
//get all the product_title that contains "NEW"
let contains_new = $(".product_title:contains(NEW)");
for(let x = 0; x < contains_new.length; x++) {
//store the previous html value
let prev_html = contains_new[x].innerHTML;
//remove the "NEW" word in the prev_html
let new_html = prev_html.replace('NEW','');
//update the inner html
contains_new[x].innerHTML = `<span class"new">NEW</span>${new_html}`;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2 class="product_title">NEW Jeep Wrangler</h2>
<h2 class="product_title">NEW Jeep Wrangler</h2>
try to inspect element the result to view the html structure.
Something like this could work:
$('h2').each((i)=>{
txt=$(i).text().split(' ')
i_html = `
<span class ='${txt[0]}.toLocaleLowerCase()' >${txt.pop(0)}</span> ${txt.join(' ')}
`
$(i).html(i_html)
})
If you just want to do it for certain words, create a array with them and check with keywords.include(txt[0])

How to insert elements into html document from string?

I have a string of html code stored in the localStorage, and what I want is to convert that string into a document and add that doc to an existing page. So far I came up with:
var data = localStorage.getItem("data");
var frag = document.createRange().createContextualFragment(data);
document.body.appendChild(frag);
but in the page the document fragment is just a simple string.
EDIT
I currently have the html:
<html>
<head>
</head>
<body>
</body>
</html>
The string I saved for test purpose to the localStorage was <p>Test</p>
The result I am trying to get:
<html>
<head>
</head>
<body>
<p>Test</p>
</body>
</html>
The result I get:
<html>
<head>
</head>
<body>
"<p>Test</p>"
</body>
</html>
If the text in local storage is HTML, you can insert it at the beginning of, at the end of, in front of, or after any other existing element by using insertAdjacentHTML. For example, to add to the document using the HTML in html inside the document body at the end:
document.body.insertAdjacentHTML("beforeend", html);
Example:
const html = "<p>This is a new paragraph with <em>emphasized</em> text.</p>";
document.body.insertAdjacentHTML("beforeend", html);
<p>This paragraph is already on the page.</p>
You can also use the innerHTML property of an existing element if you want to completely remove that element's current contents and replace them with what's defined in the HTML string:
someElement.innerHTML = html;
Example:
const html = "This is the new content for the paragraph, with <em>emphasized</em> text.";
document.getElementById("existing-paragraph").innerHTML = html;
<p id="existing-paragraph">This paragraph is already on the page.</p>
If it's not HTML, you can put it in an element (such as a p or div) and append that somewhere via appendChild or insertBefore, e.g.:
const p = document.createElement("p");
p.textContent = text;
document.body.appendChild(p);
Example:
const text = "This is plain text, so things like <this> don't get misinterpreted as HTML.";
const p = document.createElement("p");
p.textContent = text;
document.body.appendChild(p);
Or just append it as raw text using createTextNode:
const textNode = document.createTextNode(text);
document.body.appendChild(textNode);
Example:
const text = "This is plain text, so things like <this> don't get misinterpreted as HTML.";
const textNode = document.createTextNode(text);
document.body.appendChild(textNode);
There's lots more to explore on MDN.
In the comments we've figured out that the text in local storage has already been HTML-encoded, like this:
<p>Testing <em> one two three</em></p>
That means that whatever code put the text in local storage encoded it before doing that (because local storage doesn't do that; it faithfully stores and returns the exact string you give it). The best solution is probably to update that code so that it doesn't do that.
If you can't update that code, you can interpret that text as HTML, you just have to do it twice: Once to interpret the < and such so they're < again, then again to insert and parse the resulting HTML. The easy way to do that is to create an element (a div for instance), set its innerHTML, and then read its textContent. Here's an example:
Example:
const textFromLocalStorage = "<p>Testing <em> one two three</em></p>";
const div = document.createElement("div");
div.innerHTML = textFromLocalStorage;
const decodedHtml = div.textContent;
document.body.insertAdjacentHTML("beforeend", decodedHtml);
<p>This paragraph is already on the page.</p>
the arguments of appendChild are html elements.
When you send to this a string, it converts to textnode.
You need to use innerHTML method
may be that ?
const DomParser = new DOMParser();
let data = localStorage.getItem("data");
let frag = DomParser.parseFromString( data, 'text/html').body.firstChild
document.body.appendChild(frag);
expecting data is only 1 html element (it can have many html sub elements)
sample code
const DomParser = new DOMParser();
let data = '<p>Test</p>' // eq: localStorage.getItem("data");
let frag = DomParser.parseFromString( data, 'text/html').body.firstChild;
document.body.appendChild(frag);
p {
font-size: 30px;
color: red;
}

How to add a href into a div with Javascript

I would like to add <a href='https://google.com'> after a <div>.
Here is what I've been trying:
http://jsfiddle.net/L29e4ftj/
Is there someone who could help me out please?
Thank you!
Is that how do you want this ?
<div id="autoComplete_list">
<div data-id="2" class="autoComplete_result">
<span class="autoComplete_highlighted">google</span>
</div>
</div>
<script>
var aUrl = document.createElement("a");
aUrl.setAttribute("href", "https://google.com");
aUrl.innerHTML = "<span class='autoComplete_highlighted'>Google</span>"
document.querySelector("#autoComplete_list").appendChild(aUrl);
</script>
Problem
The way you are selecting the div is slightly wrong.
You use getElementsByClassName() which returns a list of elements, not a single element, so you will get [div] instead of div.
Solution
You can either get the first element of that list:
document.getElementsByClassName("autoComplete_result")[0]
or use the simpler Document.querySelector:
document.querySelector(".autoComplete_result") (which returns only one element, not an array).
window.onload=function() {
// Notice the [0] which selects ONLY the first matched element
var mydiv = document.getElementsByClassName("autoComplete_result")[0];
var a = document.createElement('a');
a.setAttribute('href',"https://www.google.com");
a.innerText = "google link";
mydiv.appendChild(a);
}
Seems that the getElementsByClassName is not returning as expected, so the appendChild is not working. I tried using querySelector and is working fine. Take a look at the code snippet below:
var mydiv = document.querySelector('.autoComplete_result');
var a = document.createElement('a');
a.setAttribute('href',"https://www.google.com");
a.innerText = "google link";
mydiv.appendChild(a);
<body>
<div id="autoComplete_list">
<div data-id="2" class="autoComplete_result">
<span class="autoComplete_highlighted">goog</span>le
</div>
</div>
</body>

Convert <br> to plain text

I have a sample html text:
<html>
<body>
<p>This is test<br>THIS IS TEST</p>
</body>
</html>
Now i want to get output like this to paste into excel
This is sample test<br>THIS IS TEST ( i want to get <br> tag like a string )
Because i want to get all content in <p> tag, include all <br> tag.
How can i do that ?
Thank for read.
jQuery html() should do what you need.
var content = $('p').html();
will give you:
This is test<br>THIS IS TEST
See example here
if you want to use jquery, the simplest way to get the result is use "html()" function.
var htmlcontent = $('body').html();
alert(htmlcontent );
You don't need jQuery, do it just with JavaScript:
alert(document.getElementsByTagName('p').innerHTML;)
Or if you want have more p tags:
var parag = document.getElementsByTagName('p');
for(var i=0; i<parag.length; i++)
{
alert(parag[i].innerHTML);
}

Display html link with javascript

In some part of an html page, I have a link with the following code :
<a id="idname" class="classname" href="www.MySite.com/image-name.jpg">link-text</a>
I would like to automatically display the same link in another part of the same page by using a javascript.
What would be the script to insert in my page ?
Thank you in advance for any help in this matter.
Patrick
Try this:
myVar = document.getElementById("idname");
varLink = (myVar.attributes.href);
As son as you know the target id:
<div id="targetID">New Link: </div>
<div id="targetID2">New Link 2: </div>
And If you are using jQuery you can do like this:
var link = $("#idname").clone();
link.attr("id",link.attr("id") + (Math.random() * 10));
$("#targetID").append(link);
If not:
var link = document.getElementById("idname");
var newLink = document.createElement("a");
newLink.href = link.href;
newLink.className = link.className;
newLink.innerHTML = link.innerHTML;
newLink.id = link.id + (Math.random() * 10);
document.getElementById("targetID2").appendChild(newLink);
See this Example
<script>
window.onload = function() {
// get data from link we want to copy
var aHref = document.getElementById('idname').href;
var aText = document.getElementById('idname').innerHTML;
// create new link element with data above
var a = document.createElement('a');
a.innerHTML = aText;
a.href = aHref;
// paste our link to needed place
var placeToCopy = document.getElementById('anotherplace');
placeToCopy.appendChild(a);
}
</script>
Use code above, if you want just to copy your link to another place. JSFiddle
First, I want to point out that if you will just copy the element that will throw an error because the copied element will have the same id of the first one, so if you will create a copy of your element you don't have to give it the same id.
Try this code:
function copyLink(newDestination){
var dest=document.getElementById(newDestination);
var newLink=document.createElement("a");
var myLink=document.getElementsByClassName("classname")[0];
newLink.href=myLink.href;
newLink.className = myLink.className;
newLink.innerHTML = myLink.innerHTML;
newDestination.appendChild(newLink);
}
The newDestination parameter is the container element of the new Link.
For example if the new Container element has the id "div1":
window.onload = function() {
copyLink(div1);
}
Here's a DEMO.
Thank you very much to everyone for so many prompt replies.
Finally, I was able to use Jquery.
So, I tried the solution given by Andrew Lancaster.
In my page, I added the codes as follows, in this order :
1-
<span id="span1">
<a class="classname" href="www.MySite.com/image-name.jpg">link-text</a>
</span>
<p>
<span id="span2"></span>
</p>
and further down the page :
2-
<script type="text/javascript">
var span1val = $('#span1').html();
$('#span2').html(span1val);
</script>
Therefore, the two expected identical links are properly displayed.
But, unfortunately, I forgot to say something in my initial request:
the original link is in the bottom part of my page
I would like to have the duplicated link in a upper part of my page
So, would you know how to have the duplicated link above the original link ?
By the way, to solve the invalid markup mentioned by David, I just deleted id="idname" from the original link (that I could ignored or replaced by other means).
Thank you again in advance for any new reply.
Patrick
Using Jquery you could wrap your link in a span with an ID and then get the value of that ID and push it into another span id.
HTML
<span id="span1">
<a id="idname" class="classname" href="www.MySite.com/image-name.jpg">link-text</a>
</span>
<p>
<span id="span2"></span>
</p>
jQuery
var span1val = $('#span1').html();
$('#span2').html(span1val);
Example can be found here.
http://jsfiddle.net/3en2Lgmu/5/

Categories