I have a string which contains this text:
<!DOCTYPE html>
<html>
<head>
<title>ExtractDiv test</title>
</head>
<body>
<p>Apples and oranges</p>
<div id="main">
<ul style="list-style-type: upper-roman">
<li>Äpfel</li>
<li>Birnen</li>
</ul>
</div>
<p>Men and women</p>
</body>
</html>
Now I need a JavaScript function which gives me back a DOM element with a specific ID as a string from this text, for example:
function ExtractElementByIdFromString(HTMLString, IdString)
{
var ExtractedElement = ???(HTMLString, IdString);
return ExtractedElement;
}
So the RESULT of this function in this case would be:
<div id="main">
<ul style="list-style-type: upper-roman">
<li>Äpfel</li>
<li>Birnen</li>
</ul>
</div>
Is this possible?
You can parse an HTML string with the native DOMParser:
var str = "<!DOCTYPE……………" // your HTML string
var doc = new DOMParser().parseFromString(str, "text/html")
Then just use regular DOM methods:
console.log( doc.getElementById("main") )
Note that using a DOMParser is more efficient and safer than inserting the string somewhere in your document's innerHTML, because only the structure will be created — <script> elements won't be executed, images won't be loaded, CSS will no try to apply to it, no rendering will occur, etc.
You can create a temporary element, put the HTMLString as a content to it, then use querySelector to get an element with passed id. Something like this:
function ExtractElementByIdFromString(HTMLString, IdString) {
var result,
temp = document.createElement('div'); // Create a temporary element
temp.innerHTML = HTMLString; // Set the passed string as HTML to the temporary element
result = temp.querySelector('#' + IdString).outerHTML; // Find an element with the passed id
return result;
}
A working demo at jsFiddle.
Related
I use ajax get a json like this:
{"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"}
How to append "delete_flag" , "id" , "icon_img" to 3 different places on html ?
You can use this pure javascript method like below.
The code basically uses document.getElementById() to get the element, and .innerHTML to set the inside of the element to the value of the object.
This code (and the code using jQuery) both use JSON.parse() to parse the data into the correct object that our code can read. The [0] at the end is to select the object we wanted since it would give us an array (and we want an object).
const result = {"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"};
const parsedData = JSON.parse(result.dataStore)[0];
document.getElementById("delete_flag").innerHTML = parsedData.delete_flag;
document.getElementById("id").innerHTML = parsedData.id;
document.getElementById("icon_img").src = parsedData.icon_img;
<div id="delete_flag"></div>
<div id="id"></div>
<img id="icon_img">
Or you can use jQuery (which in my opinion, is much simpler). The code below uses .html() to change the inside of the divs to the item from the object, and .attr() to set the attribute src to the image source you wanted.
const result = {"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"};
const parsedData = JSON.parse(result.dataStore)[0];
$("#delete_flag").html(parsedData.delete_flag);
$("#id").html(parsedData.id);
$("#icon_img").attr("src", parsedData.icon_img);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="delete_flag"></div>
<div id="id"></div>
<img id="icon_img">
you can use jQuery .html() or .text()
For example:
var json = {"id" : "74"};
$( "#content" )
.html( "<span>This is the ID: " + json.id + "</span>" );
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="content"></div>
</body>
</html>
Just use some simple JavaScript parsing:
const jsonData = {"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"};
const parsedData = JSON.parse(jsonData.dataStore)[0];
document.getElementById("delFlag").textContent = "Delete Flag: " + parsedData["delete_flag"];
document.getElementById("id").textContent = "ID: " + parsedData["id"];
document.getElementById("img").textContent = "Image: " + parsedData["icon_img"];
<p id="delFlag"></p>
<p id="id"></p>
<p id="img"></p>
Note that you can't parse the full object jsonData because it's not JSON - only the data inside it is JSON.
I've upvoted the other answers, but maybe this will help someone else. On your ajax success function, do something like this:
success: function(data){
// console.log('succes: '+data);
var delete_flag = data['delete_flag'];
$('#results').html(delete_flag); // update the DIV or whatever element
}
if you got real fancy, you could create a for loop and put all the json variable you need into an array and create a function to parse them all into their proper elements; you could learn this on your own fairly easily.
var data = {
"dataStore": {
"delete_flag": "false",
id: "74"
}
}
$('.flag').html(data.dataStore.delete_flag);
$('.id').html(data.dataStore.id);
span {
color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Flag: <span class="flag"></span>
<hr />
ID: <span class="id"></span>
Please, code to change domain in href (html, JavaScript).
Exemple:
<a id="NewL" href="http://exemple.com/indice.html">Indice</a>
To:
<a id="NewL" href="http://exemple.net/indice.html">Indice</a>
Exemple code not working:
<script type = "text/javascript" >
function replace() {
var aEls = document.getElementById('NewL').getElementsByTagName('a');
aEls.href = aEls.href.replace('http://exemple\.com', 'http://exemple\.net');
}
</script>
Thanks, #t.niese:
<a id="NewL" href="http://exemple.com/indice.html">Indice</a>
<script type="text/javascript" >
function replace() {
var aEl = document.getElementById('NewL');
aEl.href = aEl.href.replace('http://exemple.com', 'http://exemple.net');
}
replace();
</script>
Please help me, not change in various ID in same page:
<a id="NewL" href="http://exemple.com/indice.html">Indice</a>
<a id="NewL" href="http://exemple.com/indice2.html">Indice 2</a>
<script type="text/javascript" >
function replace() {
var aEl = document.getElementById('NewL');
aEl.href = aEl.href.replace('http://exemple.com', 'http://exemple.net');
}
replace();
</script>
Element.getElementsByTagName():
[...]The subtree underneath the specified element is searched, excluding the element itself.[...]
so you search for the elements with the tag name a within your element with the id NewL
Because document.getElementById('NewL') is already your a element, you won't need the getElementsByTagName('a'), as of that you should only write:
var aEl = document.getElementById('NewL');
Also your replace is wrong, you don't need to escape the . if you pass the search as string.
aEl.href = aEl.href.replace('htp://exemple.com', 'htp://exemple.net');
Beside that Element.getElementsByTagName() returns a list of elements, so even if your search would have been correct, you would need to use a loop to iterate through that result.
change your javascript to the following:
<script type = "text/javascript" >
function replace() {
var aEl = document.getElementById('NewL');
aEl.href = aEl.href.replace('htp://exemple\.com', 'htp://exemple\.net');
}
</script>
You already selected the element by the getElementById no need to find the a class in it. Also you mispelled the variable which I changed to aEl
The code
var txt = '<div id="hi">fe</div><div id="h2">fe</div><div id="hj">fe</div>'
var parser = new DOMParser();
var temp_node = parser.parseFromString(txt, "text/html").documentElement;
console.log(temp_node)
This code results in the full html document, this is including
<html><head></head><body>
<div id="hi">fe</div>
<div id="h2">fe</div>
<div id="hj">fe</div>
</body></html>
What if I want only the <div id="hi">fe</div><div id="h2">fe</div><div id="hj">fe</div> part? How can I do it?
And, if I want to append all nodes, is there a way to do it without a loop?
parentNode.appendChile(temp_node) // add the entire code
parentNode.appendChile(temp_node.firstElementChild.nextElementSibling) // add the parent <body> and the other layers inside
parentNode.appendChild(temp_node.firstElementChild.nextElementSibling.childNodes) // doesn't do the trick, it complains about not being a "node", I guess I'd need an "appendChilds" function that allows to add many nodes at once
*What I'd wish, if parentNode is <div id="parent">
<div id="parent">
<div id="hi">fe</div>
<div id="h2">fe</div>
<div id="hj">fe</div>
</div>
But I get
<div id="parent">
<body>
<div id="hi">fe</div>
<div id="h2">fe</div>
<div id="hj">fe</div>
</body>
</div>
Use childNodes
console.log(temp_node.childNodes[1].childNodes[0]);
or querySelector
console.log(temp_node.querySelector("#hi"));
JSFiddle demo
Update
or innerHTML
console.log(temp_node.querySelector("body").innerHTML);
JSFiddle demo
The property documentElement returns the following:
Returns the Element that is a direct child of the document. For HTML
documents, this is normally the HTMLHtmlElement object representing
the document's <html> element.
- MDN
There are other properties that exist on the Document, .body is one of which. Using .body (instead of querySelector) will give you fast direct access to the body of your HTML content, which you can then use .innerHTML on to get its inner contents:
parser.parseFromString(txt, "text/html").body
See working example:
const txt = '<div id="hi">fe</div><div id="h2">fe</div><div id="hj">fe</div>'
const parser = new DOMParser();
const temp_node = parser.parseFromString(txt, "text/html").body;
console.log(temp_node.innerHTML);
I have the following code and I want to remove placeholder.
<div class="myclass">
<p>[Sitetile][change this too]someothercontent</p>
</div>
and I want to change the above markup to this with some event using jQuery:
<div class="otherclass">
<p>changemaincontentchangesomeothercontent</p>
</div>
Create an object with the index named as the part you want to replace (inside the brackets) and assign the value to it. Then use the $.each-function to iterate over the object and replace the values in the html with the one from the object. After that assign the new html-string to your element.
var change = {
'Sitename': 'yahoo.com',
'Sitetile': 'changemaincontent',
'change this too': 'change'
};
var $elem = $('.myclass > p'); //cache the element
var html =$elem.html(); //get the html-string
$.each(change, function(index, value){ //iterate over the object
html = html.replace('[' + index + ']', value); //replace the values
});
$elem.html(html); //assign the new html-string
Demo
Reference
.replace()
$.each()
.html()
you need to put someothercontent in <span>
HTML
<div class="myclass">
<p>
maincontent
<span>someothercontent</span>
</p>
</div>
Script
$('.myclass').find('a').text('changemaincontent');
$('.myclass').find('span').text('changesomeothercontent');
Demo
You can try some thing like this !!!
<<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id='link'><a href='javascript:open_fun()'>OPEN</a></div>
</body>
</html>
<script type="text/javascript">
function close_fun() {
document.getElementById('link').innerHTML = "<a href='javascript:open_fun()'>OPEN</a>";
}
function open_fun() {
document.getElementById('link').innerHTML = "<a href='javascript:close_fun()'>CLOSE</a>";
}
</script>
Hope this helps !!!
How to get number of HTML elements (HTML tags) in a string?
For example I have this string:
<div> some text
<div>
<label>some text</label>
</div>
</div>
Now how would I find number of html tags in this string? The result in the case above will be 3.
I did tried this, thought it will work but it didn't:
$('*').length;
var s = "<div> some text<div><label>some text</label></div></div>";
var length = $(s).find('*').andSelf().length;
http://jsfiddle.net/jCW7Z/
If you're using jQuery (and it looks like you are), the easiest way would be to use code similar to the following:
var count = $( yourString ).find('*').andSelf().length
However, if you're using vanilla javascript, the implementation would look more like this:
var temp = document.createElement('div');
temp.innerHTML = yourString;
var count = temp.getElementsByTagName('*').length;
Get all elements in the document (document.getElementsByTagName('*'))
Do a regular expression match on the element's className attribute for each element
You can use jQuery: $("html *") which will return all elements between the html tags
for names you must use $("html *").attr('name')
for values $("html *").val() or $("html *").attr('value')
Possible way to do it: http://api.jquery.com/length/
check out Find number of element in string with jQuery
for example
$( '.myClass', myData ).length;
(although this might not show outermost tags)
You can do it like this,
Put the string in to some hidden div like
$('#myHiddenDiv').html(string);
then
You can gen number of children under it
This will tell you number of html elements under the body
var count = $("#myHiddenDiv> *").length;
or:
var count = $("#myHiddenDiv").children().length;
Your div will be like this
<div id="myHiddenDiv" style="display:none"></div>
A small, self documenting, example :)
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>List Elements</title>
</head>
<body>
<div>some text
<div>
<label>some text</label>
</div>
</div>
<script>
var x=document.getElementsByTagName('*');
console.log(x.length)
for (i=0;i<x.length;i++) {
console.log(x[i]);
}
</script>
</body>
</html>