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);
});
Related
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'));
I have some js code that has been imported from another file which has a variable in it I want to update in my HTML file. How can I update the variable without pasting the js code into my HTML file?
JS (script.js):
var link = "https://example.com"
var codeBlock = `...some html code... ${link} ...some more html code`;
document.getElementById("div").innerHTML = codeBlock
HTML:
<div id="div"></div>
<script src= "script.js"></script>
<script>
//I want to change this variable
var link = "https://anotherexample.com"
</script>
On line one of your code, you declare link and give it a value.
On line two, you use that value.
You can't change link later on and affect what happened when the value was read and used in the past.
If you want to change the final result, then it is the final result you have to change (i.e. you need to assign a new value to document.getElementById("div").innerHTML).
You are getting the value but not setting it to the variable that the HTML is showing.Is this you are looking for :
var updatedLink = document.getElementById("anotherlink").innerHTML;
var codeBlock = `...some html code... ${updatedLink} ...some more html code`;
document.getElementById("div").innerHTML = codeBlock
<div id="div"></div>
<div id="anotherlink" style="display:none"></div>
<script src= "script.js"></script>
<script>
var link = "https://anotherexample.com";
document.getElementById("anotherlink").innerHTML = link
</script>
Your script is working and the variable is being changed. If you console.log(link) after declaring it again, you'll see the variable has changed. If you're expecting the script to execute again, that won't happen without calling it again.
What you may want to try is iterating through the document looking for something to trigger that statement, for example, links in the document.
const links = document.querySelectorAll('a');
var href = [];
links.forEach(link => href.push(link.href));
var codeBlock = '';
href.forEach(link => {
if (link == "https://stacksnippets.net/anotherexample.com") {
codeBlock = `...some html code... ${link} ...some more html code`;
document.getElementById('div').innerHTML = codeBlock;
}
})
<div id="div">link</div>
Or without checking for a specific URL:
const links = document.querySelectorAll('a');
var href = [];
links.forEach(link => href.push(link.href));
var codeBlock = '';
href.forEach(link => {
codeBlock = `...some html code... ${link} ...some more html code`;
document.getElementById('div').innerHTML = codeBlock;
})
<div id="div">link</div>
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.
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 !!!
I have a image with link
<div id="img"><img src="/src/img.png"/></div>
but i don't wanna use tag for linking.the page has multiple entries like this in a page as it is being populated for a search result.Some 10 or more entries will be there in a page.its all inside a <div id="result"></div>
have an idea for doing it dojo.help me finish that
function(){
dojo.query('.Result').forEach(function(item){
try{
var href = dojo.query('.img',item)[0]
//do things
dojo.connect(Node,'onclick',dojo.hitch(this,function(){
window.location = location;
}));
Try the code below:
<div id="result">
<div class="imageContainer"><img location="src/blah.html" src="/src/img.png"></div>
</div>
dojo.query("#result .imageContainer img").connect("onclick", function() {
var location = dojo.attr(this, "location");
if (location) {
window.location.href = location;
}
});