There is the following HTML code:
<body>
<menu>
</menu>
... other html
</body>
I need to replace <menu> tag with HTML content from variable. I know how I can change innerHTML using string variable with content (variable 'template');
menu.innerHTML = template;
Variable 'template' contains '<ul class="menu"></ul>'. As result I want to have the following HTML:
<body>
<ul class="menu">
</ul>
... other html
</body>
You mention innerHTML; there's a corresponding outerHTML property that, when set, will replace the element and all children with your update:
var menu = document.getElementsByTagName('menu')[0];
menu.outerHTML = template;
Try:
var body = document.getElementsByTagName('body')[0];
body.innerHTML = body.innerHTML.replace(/<menu>[\s\S]*?<\/menu>/, template);
Try this
var str = '<ul class="menu"></ul>';
var menu = document.getElementsByName('menu');
var parentMenu = menu.parentNode;
parentMenu.removeChild(menu);
parentMenu.innerHTML = str + parentMenu.innerHTML;
try this
var elem = document.getElementsByTagName('body')[0]; // Select any element you want.
var target = elem.innerHTML;
elem.innerHTML = target.replace(/(<menu)/igm, '<ul class="menu"').replace(/<\/menu>/igm, '</ul>');
Related
I'm working on the tooltips and from the backend I'll get data in with html tags. I need to show in the tooltip with its corresponding data in its respective tags. For example, I'll get hello user click here from the backend. I've to show as hello user in h1 format and click here should be a anchor. I tried with both functions and replace its not working.
With function:
<h1 id="data">
</h1>
function convertToPlain(html){
var tempDivElement = document.createElement("div");
tempDivElement.innerHTML = html;
return tempDivElement.textContent || tempDivElement.innerText || "";
}
var htmlString= "<div><h1>Bears Beets Battlestar Galactica </h1>\n<p>Quote by Dwight Schrute<a> click here<a></p></div>";
let dataVal = convertToPlain(htmlString)
document.getElementById("demo").innerHTML = dataVal;
With replace:
https://codesandbox.io/s/serene-fast-u8fie?file=/App.svelte
I made below snippet by copy-paste your code and just update return statement inside convertToPlain function, also I added href attribute to <a> in the htmlString content.
function convertToPlain(html) {
var tempDivElement = document.createElement("div");
tempDivElement.innerHTML = html;
return tempDivElement.innerHTML;
}
var htmlString = "<div><h1>Bears Beets Battlestar Galactica </h1>\n<p>Quote by Dwight Schrute<a href='#'> click here<a></p></div>";
let dataVal = convertToPlain(htmlString)
document.getElementById("demo").innerHTML = dataVal;
<h1 id="demo"></h1>
I am looking for a way how I can insert things before an element in plain javascript.
I have a footer element:
//html
<footer>
...
</footer>
// js
var footer = document.querySelector('footer')
and I want to add this string containing html before it:
var string = "<div class='sun'><p>hi and more things</p>...</div>"
In jQuery I'd simply do this:
$(footer).before(string)
But how I can do it in plain javascript? How to convert the string to NODE and then display?
You can use .insertAdjacentHTML('beforebegin', string)
var string = "<div class='sun'><p>hi and more things</p>...</div>"
document.querySelector('footer').insertAdjacentHTML('beforebegin', string);
<footer>Footer</footer>
Try like this .Better do with createElement() instead of string element creation in dom
parentNode.insertBefore(newnode, existingnode)
var footer = document.querySelector('footer')
var string = document.createElement('div')
string.class='sun'
string.innerHTML ='<p>hi and more things</p>'
document.body.insertBefore(string,footer)
<footer>
footer
</footer>
var fragment = document.createDocumentFragment();
fragment.innerHTML = "<div class='sun'><p>hi and more things</p>...</div>";
var footer = document.querySelector('footer');
document.body.insertBefore(fragment, footer);
I have this source
<div class="page"><h1>First Page </h1></div>
How can I convert it to html and use selector like $('.page') ? I tried to assign above string to a variable then use html() it doesn't work.
You can parse your string in HTML, after that if you look the object returned, there's a data property on the first row who contain the html string with good format.
EDIT
You can get HTML object properties without append it to the DOM. Check my edited code.
var test = '<div class="page"><h1>First Page </h1></div>';
var testHTML = $.parseHTML(test);
var elemHTML = $(testHTML[0].data);
console.log(elemHTML.text());
You can try this :
var test = '<div class="page"><h1>First Page </h1></div>';
var testHTML = $.parseHTML(test);
$("body").html(testHTML[0].data);
$(".page").css("color","blue");
//Without append element in the DOM
var elemHTML = $(testHTML[0].data);
console.log(elemHTML.text());
//For count number of element you can use a container without append it to the DOM
var container=$("<div></div>");
container.append(elemHTML);
console.log(container.find(".page").length);
.page{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
See comments, first we have to process the entities, then use the result as HTML:
// The string
var str = '<div class="page"><h1>First Page </h1></div>';
// A wrapper element to put it in
var wrapper = $("<body>");
// Process the character entities
wrapper.html(str);
str = wrapper.text();
// Convert the resulting HTML to a structure
wrapper.html(str);
console.log("Text of .page: ", wrapper.find(".page").text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
That's verbose for clarity; here's the concise version:
var str = '<div class="page"><h1>First Page </h1></div>';
var wrapper = $("<body>");
wrapper.html(wrapper.html(str).text());
console.log("Text of .page: ", wrapper.find(".page").text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use following script for this
$('.page').html('<div class="page"><h1>First Page </h1></div>');
or
var htmlString = '<div class="page"><h1>First Page </h1></div>';
$('.page').html(htmlString);
Jquery automatically convert it to html
I'm trying to learn HTML and Javascript/jQuery. If I have a container which holds a title, an image, a description and a number, then I want to create a new container with the exact same format (except the values will be different), how is this commonly done?
This is an example of the format I'm looking for in each item.
<li>
<div>
<div>
Image Name
</div>
<div>
<a href=URL>
<img src='image_url'>
</a>
</div>
<div>
Description
</div>
<div>
num_comment Comments
</div>
</div>
</li>
Do I just create a string and concatenate with the actual values for the image, then add that string to some variable I've saved called html_content, and then set the html value to html_content? Is that the common way of doing this or is there a better way?
EDIT
To give a better idea of what I'm currently doing, here's the javascript:
var html1 = '<li><div><div>';
var html2 = '</div><div><a href="';
var html3 = '"><img src="';
var html4 = '"></a></div><div>';
var html5 = '</div><div>';
var html6 = '</div></div></li>';
function render(pics){
for (var i in pics){
html = html + html1 + pics[i].name + html2 + pics[i].image_url + html3 + ...
};
$('pics').html(html);
}
In jQuery you just have to use the append() function to add on to something.
You could do something like...
$('select element').append('<li><div>....etc.');
and where you want a different value you can use a variable.
You can use .clone() and create a copy of this, then iterate through the cloned object and change what you need:
var $objClone = $("li").clone(true);
$objClone.find("*").each(function() {
//iterates over every element. customize this to find elements you need.
});
To change the image source you can do:
$objClone.find("img").attr("src", "new/img/here.jpg");
Fiddle demoing the concept: http://jsfiddle.net/H9DnA/1/
You may find it useful to explore some of the JavaScript templating libraries. The essential idea is that you create a template of your markup:
<li>
<div>
<div>
{{name}}
</div>
<div>
<a href="{{url}}">
<img src="{{imageUrl}}">
</a>
</div>
<div>
{{description}}
</div>
<div>
{{comments}}
</div>
</div>
</li>
Then you merge it against some associated matching object and insert it into your document:
{ name: 'Image Name',
url: 'http://example.com',
imageUrl: 'http://example.com/image.jpg',
description: 'Description',
comments [ { text: 'Comment' } ]
}
function render(pics)
{
var theList = document.getElementByid("LIST ID");
for (var i in pics){
var listItem = document.createElement('li'); // Create new list item
var nameDiv = document.createElement('div'); // Create name DIV element
nameDiv.innerHTML = pics[i].name; // Insert the name in the div
var img = document.createElement('img'); // Create Img element
img.setAttribute('src',pics[i].src); // Assign the src attribute of your img
var imgDiv = document.createElement('div'); // Create Img Div that contains your img
imgDiv.appendChild(img); // Puts img inside the img DIV container
var descDiv = document.createElement('div'); // Create Description DIV
descDiv.innerHTML = pics[i].description; // Insert your description
listItem.appendChild(nameDiv); // Insert all of you DIVs
listItem.appendChild(imgDiv); // inside your list item
listItem.appendChild(descDiv); // with appropriate order.
theList.appendChild(listItem); // Insert the list item inside your list.
}
}
I think this will work just fine:
$('#button').click(function () {
var html1 = '<li><div><div>';
var html2 = '</div><div><a href="';
var html3 = '"><img src="';
var html4 = '"></a></div><div>';
var html5 = '</div><div>';
var html6 = '</div></div></li>';
function render(pics){
for (var i in pics){
html = html + html1 + pics[i].name + html2 + pics[i].image_url + html3 + ...
$("ul").append(html);
}
}
// call render
});
I didn't do a test run on your code so there might be an error somewhere. My tweak adds this line $("ul").append(html); inside your loop
var theNewParagraph = document.createElement('p');
var theBoldBit = document.createElement('b');
var theBR = document.createElement('br');
theNewParagraph.setAttribute('title','The test paragraph');
var theText1 = document.createTextNode('This is a sample of some ');
var theText2 = document.createTextNode('HTML you might');
var theText3 = document.createTextNode('have');
var theText4 = document.createTextNode(' in your document');
theBoldBit.appendChild(theText2);
theBoldBit.appendChild(theBR);
theBoldBit.appendChild(theText3);
theNewParagraph.appendChild(theText1);
theNewParagraph.appendChild(theBoldBit);
theNewParagraph.appendChild(theText4);
document.getElementById('someElementId').appendChild(theNewParagraph);
Also, can anyone help me by explaining this?
What you have is a snippet of JavaScript code. I've added comments to the code to explain each section:
// Create 3 elements, a <p>, a <b> and a <br>
var theNewParagraph = document.createElement('p');
var theBoldBit = document.createElement('b');
var theBR = document.createElement('br');
// Set the title attribute of the <p> element we created
theNewParagraph.setAttribute('title','The test paragraph');
// Create 4 "text nodes", these appear as text when added to elements
var theText1 = document.createTextNode('This is a sample of some ');
var theText2 = document.createTextNode('HTML you might');
var theText3 = document.createTextNode('have');
var theText4 = document.createTextNode(' in your document');
/* Add the second text node, the <br> element and the 3rd text node to the
<b> element we created */
theBoldBit.appendChild(theText2);
theBoldBit.appendChild(theBR);
theBoldBit.appendChild(theText3);
/* Add the first text node, the <b> element and the 4th text node to the
<p> element we created. All nodes are now descendants of the <p> */
theNewParagraph.appendChild(theText1);
theNewParagraph.appendChild(theBoldBit);
theNewParagraph.appendChild(theText4);
/* Finally, add the <p> element to an element with an id attribute of
someElementId, so we can see all the content on our page */
document.getElementById('someElementId').appendChild(theNewParagraph);
The result is the following HTML as the content of someElementId:
<p title="The test paragraph">This is a sample of some <b>HTML you might<br>
have</b> in your document</p>
Others have explained how to add this script to your document using the <script> element.
Put the above in a <script type="text/javascript"> at the bottom of your page and make sure there's an <div id="someElementId"> in your document.
What it's doing is creating a new <p>, <b> and <br> tag. It then sets the title on the paragraph, adds some text to all tags and finally adds the whole mess to an element with id #someElementId.
You can see it in action here.
Here is a suitable test harness. Paste the following into a new .html file:
<html><head><script language="javascript"><!--// your javascript here:
function _onload()
{
var theNewParagraph = document.createElement('p');
var theBoldBit = document.createElement('b');
var theBR = document.createElement('br');
theNewParagraph.setAttribute('title','The test paragraph');
var theText1 = document.createTextNode('This is a sample of some ');
var theText2 = document.createTextNode('HTML you might');
var theText3 = document.createTextNode('have');
var theText4 = document.createTextNode(' in your document');
theBoldBit.appendChild(theText2);
theBoldBit.appendChild(theBR);
theBoldBit.appendChild(theText3);
theNewParagraph.appendChild(theText1);
theNewParagraph.appendChild(theBoldBit);
theNewParagraph.appendChild(theText4);
document.getElementById('someElementId').appendChild(theNewParagraph);
}
//--></script></head><body onload='_onload()' id='someElementId'></body></html>
How to run:
<head>
<script type="text/javascript">
function CreateTestParagraph () {
var theNewParagraph = document.createElement('p');
var theBoldBit = document.createElement('b');
var theBR = document.createElement('br');
theNewParagraph.setAttribute('title','The test paragraph');
var theText1 = document.createTextNode('This is a sample of some ');
var theText2 = document.createTextNode('HTML you might');
var theText3 = document.createTextNode('have');
var theText4 = document.createTextNode(' in your document');
theBoldBit.appendChild(theText2);
theBoldBit.appendChild(theBR);
theBoldBit.appendChild(theText3);
theNewParagraph.appendChild(theText1);
theNewParagraph.appendChild(theBoldBit);
theNewParagraph.appendChild(theText4);
document.getElementById('someElementId').appendChild(theNewParagraph);
}
</script>
</head>
<body onload="CreateTestParagraph ()">
<div id="someElementId"></div>
</body>
Your CreateTestParagraph method creates the following HTML content dynamically:
<p title="The test paragraph">This is a sample of some <b>HTML you might<br>have</b> in your document</p>
and put that contents into the someElementId element.
Related links:
createElement method,
createTextNode method,
appendChild method,
getElementById method,
onload event