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);
Related
Is there a way to convert HTML like:
<div>
<span></span>
</div>
or any other HTML string into DOM element? (So that I could use appendChild()). I know that I can do .innerHTML and .innerText, but that is not what I want -- I literally want to be capable of converting a dynamic HTML string into a DOM element so that I could pass it in a .appendChild().
Update: There seems to be confusion. I have the HTML contents in a string, as a value of a variable in JavaScript. There is no HTML content in the document.
You can use a DOMParser, like so:
var xmlString = "<div id='foo'><a href='#'>Link</a><span></span></div>";
var doc = new DOMParser().parseFromString(xmlString, "text/xml");
console.log(doc.firstChild.innerHTML); // => <a href="#">Link...
console.log(doc.firstChild.firstChild.innerHTML); // => Link
You typically create a temporary parent element to which you can write the innerHTML, then extract the contents:
var wrapper= document.createElement('div');
wrapper.innerHTML= '<div><span></span></div>';
var div= wrapper.firstChild;
If the element whose outer-HTML you've got is a simple <div> as here, this is easy. If it might be something else that can't go just anywhere, you might have more problems. For example if it were a <li>, you'd have to have the parent wrapper be a <ul>.
But IE can't write innerHTML on elements like <tr> so if you had a <td> you'd have to wrap the whole HTML string in <table><tbody><tr>...</tr></tbody></table>, write that to innerHTML and extricate the actual <td> you wanted from a couple of levels down.
Why not use insertAdjacentHTML
for example:
// <div id="one">one</div>
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>here
Check out John Resig's pure JavaScript HTML parser.
EDIT: if you want the browser to parse the HTML for you, innerHTML is exactly what you want. From this SO question:
var tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlString;
Okay, I realized the answer myself, after I had to think about other people's answers. :P
var htmlContent = ... // a response via AJAX containing HTML
var e = document.createElement('div');
e.setAttribute('style', 'display: none;');
e.innerHTML = htmlContent;
document.body.appendChild(e);
var htmlConvertedIntoDom = e.lastChild.childNodes; // the HTML converted into a DOM element :), now let's remove the
document.body.removeChild(e);
Here is a little code that is useful.
var uiHelper = function () {
var htmls = {};
var getHTML = function (url) {
/// <summary>Returns HTML in a string format</summary>
/// <param name="url" type="string">The url to the file with the HTML</param>
if (!htmls[url])
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, false);
xmlhttp.send();
htmls[url] = xmlhttp.responseText;
};
return htmls[url];
};
return {
getHTML: getHTML
};
}();
--Convert the HTML string into a DOM Element
String.prototype.toDomElement = function () {
var wrapper = document.createElement('div');
wrapper.innerHTML = this;
var df= document.createDocumentFragment();
return df.addChilds(wrapper.children);
};
--prototype helper
HTMLElement.prototype.addChilds = function (newChilds) {
/// <summary>Add an array of child elements</summary>
/// <param name="newChilds" type="Array">Array of HTMLElements to add to this HTMLElement</param>
/// <returns type="this" />
for (var i = 0; i < newChilds.length; i += 1) { this.appendChild(newChilds[i]); };
return this;
};
--Usage
thatHTML = uiHelper.getHTML('/Scripts/elevation/ui/add/html/add.txt').toDomElement();
Just give an id to the element and process it normally eg:
<div id="dv">
<span></span>
</div>
Now you can do like:
var div = document.getElementById('dv');
div.appendChild(......);
Or with jQuery:
$('#dv').get(0).appendChild(........);
You can do it like this:
String.prototype.toDOM=function(){
var d=document
,i
,a=d.createElement("div")
,b=d.createDocumentFragment();
a.innerHTML=this;
while(i=a.firstChild)b.appendChild(i);
return b;
};
var foo="<img src='//placekitten.com/100/100'>foo<i>bar</i>".toDOM();
document.body.appendChild(foo);
Alternatively, you can also wrap you html while it was getting converted to a string using,
JSON.stringify()
and later when you want to unwrap html from a html string, use
JSON.parse()
I want to extract all the HTML tags like from this <body id = "myid"> .... </body> i just want to extract <body id ="myid"> similarly i want to extract all the HTML tags with attributes and using javascript.
I've tried using regex to make an array of all the tags inclosed between '< & >'
<script>
$(document).ready(function(){
// Get value on button click and show alert
$("#btn_parse").click(function(){
var str = $("#data").val();
var arr = str.split(/[<>]/);
$('#result').text(arr);
});
});
</script>
but it's creating an array arr containing empty and garbage also it's removing angular brackets '<>'
which I don't want.
SO in nutshell I want a script that takes
str ='mystring ... <htmltag id='myid' class='myclass'>i_don't_want_anythin_from_here</htmltag> ...';
and produces an array like:
arr = ["<htmltag id='myid' class='myclass'>","</htmltag>",...];
Here is one dirty way. Add it to the dom so it can be accessed via normal DOM functions, then remove the text, and split the tags and push to an array.
str ="mystring ... <htmltag id='myid' class='myclass'>i_don't_want_anythin_from_here</htmltag> ...";
div = document.createElement("div");
div.innerHTML = str;
document.body.appendChild(div);
tags = div.querySelectorAll("*");
stripped = [];
tags.forEach(function(tag){
tag.innerHTML = "";
_tag = tag.outerHTML.replace("></",">~</");
stripped.push(_tag.split("~"));
});
console.log(stripped);
document.body.removeChild(div);
Assuming you can also get the input from a "live" page then the following should do what you want:
[...document.querySelectorAll("*")]
.map(el=>el.outerHTML.match(/[^>]+>/)[0]+"</"+el.tagName.toLowerCase()+">")
The above will combine the beginning and end tags into one string like
<div class="js-ac-results overflow-y-auto hmx3 d-none"></div>
And here is the same code applied on an arbitrary string:
var mystring="<div class='all'><htmltag id='myid' class='myclass'>i_don't_want_anythin_from_here</htmltag><p>another paragraph</p></div>";
const div=document.createElement("div");
div.innerHTML=mystring;
let res=[...div.querySelectorAll("*")].map(el=>el.outerHTML.match(/[^>]+>/)[0]+"</"+el.tagName.toLowerCase()+">")
console.log(res)
I have this string (not html but string):
<div class="rTag">ATINA</div><div class="rTag">BELMOPAN</div><div class="rTag">DAMASK</div><div class="rTag">FILIPINI</div><div class="rTag">BANGKOK</div>
Need to extract text value of rTag so result should be a new string:
ATINA,BELMOPAN,DAMASK,FILIPINI,BANGKOK
Any help?
This will set the content of #output to the new str, but you can do whatever you want after its joined.
var str = [];
var content = '<div class="rTag">ATINA</div><div class="rTag">BELMOPAN</div><div class="rTag">DAMASK</div><div class="rTag">FILIPINI</div><div class="rTag">BANGKOK</div>';
var $html = $($.parseHTML("<div>" + content + "</div>"));
$html.find(".rTag").each(function(){
str.push($(this).html());
});
$("#output").html(str.join(","));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div id="output"></div>
Parsing an HTML string into a DOM element so that it can be processed by javascript/jquery is a fairly standard process:
$(content)
will suffice without needing to add it to the DOM (and all that entails behind the scenes).
In this case:
var content = '<div class="rTag">ATINA</div><div class="rTag">BELMOPAN</div><div class="rTag">DAMASK</div><div class="rTag">FILIPINI</div><div class="rTag">BANGKOK</div>';
var arr = $(content).filter(".rTag").map(function() {
return $(this).text();
}).get();
console.log(arr.join(","));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I have a string with some variable html saved inside, among which a div with static id="time",
example:
myString = "<div class="class">blahblah</div><div id="time">1:44</div>"
How can I create a new identical string cutting off only the time? (1:44 in this case).
I can't look for numbers or the ":" because is not safe in my situation.
What i've tried without success is this:
var content = divContainer.innerHTML;
var jHtmlObject = jQuery(content);
var editor = jQuery("<p>").append(jHtmlObject);
var myDiv = editor.find("#time");
myDiv.html() = '';
content = editor.html();
console.log('content -> '+content);
var myString = '<div class="class">blahblah</div><div id="time">1:44</div>';
//create a dummy span
//put the html in it
//find the time
//remove it's inner html
//execute end() so the jQuery object selected returns to the span
//console log the innerHTML of the span
console.log($('<span>').html(myString).find('#time').html('').end().html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can achieve this using a regular expression in plain javascript like so:
myString.replace(/(<div id="time">).*(<\/div>)/, '$1$2')
If you want to extract only the 1:44 portion you can use the following:
myString.match(/(<div id="time">)(.*)(<\/div>)/)[2]
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>');