I have a simple site. It does a fetch to another html page. That's working and I have some response. Now I want a part of the page and select the id
'test' from the HTML. Now I created a HTMLelement, but how can I select a part of it?
How can I do this without adding all the HTML to the dom.
<html>
<body>
<script>
// in real it's a fetch with response text:
const HTML = `<div id="">I dont need this</div>
<div id="test"> I want this</div>`;
const EL = document.createElement('html')
EL.innerHTML = HTML;
console.log(EL);
// This is not working, but I want to do this
console.log(EL.getElementById('test'));
</script>
</body>
</html>
Use a new DOMParser():
// in real it's a fetch with response text:
const HTML = `<div id="">I dont need this</div>
<div id="test"> I want this</div>`;
const EL = new DOMParser()
.parseFromString(HTML, "text/html")
console.log(EL.getElementById('test'));
The trick here is to create a new DOM that you can add the content to instead of creating a second HTML element belonging to your existing document.
var parser = new DOMParser();
var htmlDoc = parser.parseFromString('<div id="parent"></div>', 'text/html');
const html = `<div id="">I dont need this</div>
<div id="test"> I want this</div>`;
const el = htmlDoc.getElementById('parent');
el.innerHTML = html;
console.log(el);
// This is not working, but I want to do this
console.log(htmlDoc.getElementById('test'));
Alternatively, you can create an element belonging to the existing document and search it with querySelector (which can be called on an element) instead of document.
const html = `<div id="">I dont need this</div>
<div id="test"> I want this</div>`;
const el = document.createElement('div');
el.innerHTML = html;
console.log(el);
// This is not working, but I want to do this
console.log(el.querySelector('#test'));
Related
So in the script tag here I have an array myArr that is printed into p tag in the html:
<html>
<body>
<h1>Header 1</h1>
<div>
<p id="test"></p>
</div>
</body>
</html>
<script>
var myArr = ["abc", 123, "test"];
document.getElementById('test').innerHTML = myArr;
</script>
All that works and is good. So, I have a couple of questions about this, as I'm pretty new to javascript.
I know how to iterate through the array and print out each element within the script tag. But how would I be able to display it into the html? Is there a way to dynamically create the p tags with the element from the array as the contents?
And would I be able to easily add stying into the dynamically created p tag?
Can this kind of thing be done using something like jquery? or another popular simple javascript library?Unfortunately, I will be unable to run a full fledged javascript framework. I am only able to run a basic library.
I attempted a try here:
var my_arr = ["test", "abc", 123];
var arr_length = my_arr.length;
for (i = 0; i < arr_length; i++) {
document.createElement("p");
document.getElementById('test').innerHTML = arr_length;
my_arr[i]
}
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<div id="test">
</div>
You just need to forEach over the array. Inside the callback, create a p, append it to the desired container, and set its textContent to the array element. No frameworks/libraries required:
const test = document.getElementById('test');
const my_arr = ["test", "abc", 123];
my_arr.forEach((item) => {
test.appendChild(document.createElement('p'))
.textContent = item;
});
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<div id="test">
</div>
Array methods are generally preferrable to for loops, but if you really wanted to use a for loop like in your original code, you would have to set the textContent of the created p to my_arr[i], in addition to appending the p to test:
var my_arr = ["test", "abc", 123];
var arr_length = my_arr.length;
const test = document.getElementById('test');
for (i = 0; i < arr_length; i++) {
const p = document.createElement("p");
p.textContent = my_arr[i];
test.appendChild(p);
}
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<div id="test">
</div>
I want to convert html page div tag to json data and append that div in another html page.get that div that using id.
suppose there is page.html in which div tags are there, having id page1 page2 and so on.Convert those to json data and get the div tags according to their id, then append those div tags to page2.html div tag. how to do that.
this is page2.html
<div id="page1">
this is page1
</div>
<div id="page2">
this is page1
</div>
<div id="page3">
this is page1
</div>
<div id="page4">
this is page1
</div>
having div tags
I tried getting div using js but from another page
this is page1.html and want to access div of page2.html
function getdata()
{
$.get('page2.html', null, function(text){
alert($(text).find('#page1'));
});
var json = JSON.stringify(element);
alert(json);
}
I tried this but its not working.
you need to write div object in json string , convert div into json object with all required attributes and values.
see below snippet for example.
function append(){
var element = document.getElementById("page1");
var jsonObject = {};
jsonObject.id = element.id;
jsonObject.innerHTML = element.innerHTML;
var jsonString = JSON.stringify(jsonObject); // this is json for your div.
/// for append div and get div object back from json.
var elementProto = JSON.parse(jsonString);
var element = document.createElement("DIV");
element.innerHTML = elementProto.innerHTML;
element.id = elementProto.id;
// append to container (in your case its page 1 or 2)
document.getElementById("container").append(element);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="page1">
<p>this div will appended </p>
</div>
<button onclick="append()">append div</button>
<div id="container">
</div>
try this code for get div content
function getdata()
{
$.get('page.html', null, function(text){
alert($('#page1').html());
});
jsonObj = $('#page1').html();
var obj = $.parseJSON(jsonObj);
alert(obj );
}
Please check following code spinet in getdata()
jQuery.get('page2.html',null,function(response){
var obj = jQuery('<div/>');
var json = {};
jQuery(obj).append(response);
jQuery('[id^="page"]',obj).each(function( index, object ){
json[index] = jQuery(object).text();
});
console.log(json);
});
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.
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 want to convert the following string to HTML tags and place it inside my div.
<strong>asdfadfsafsd</strong>
I am using the following code to place it inside my div:
var message = "<strong>testmessage</strong>";
document.getElementById('message').innerHTML = bericht;
The problem is that I see the following in my div now:
<strong>testmessage</strong>
But I want to see:
testmessage
What is the problem?
var string = "<strong>asdfadfsafsd</strong>",
results = document.getElementById("results")
results.innerHTML = string;
results.innerHTML = results.textContent;
<div id="results"></div>
At first load the it as html. Then fetch it as text and then again load it as HTML :)
Refer HTML Entities
Try createElement
var tag = document.createElement("strong");
var t = document.createTextNode("testmessage");
tag.appendChild(t);
document.body.appendChild(tag);