Convert string to HTML object error - javascript

I try convert simple string to HTML object for process it with jQuery.
My code:
var old_code_text = $(invoice_template_id).html();
console.log("old text ="+old_code_text);
old_code_text=$(old_code_text);
console.log("old text2 ="+old_code_text.html());
My first alert show me:
old text =<div id="template_invoice">
<div id="first_head">
<div id="logo_invoice">
<img src="../../../images/invoice_logos/logo912131214.PNG" width="200px">
</div>
<div id="main_header_info">
....
....
</div>
</div>
But my second alert show me :
old text2 =
<div id="first_head">
<div id="logo_invoice">
<img src="../../../images/invoice_logos/logo912131214.PNG" width="200px">
</div>
<div id="main_header_info">
....
Then I use old_code_text like it:
old_code_text.find("#product_invoice_table tbody").empty();
I dont understand where is div with id template_invoice?
When I parse string this div always deleted.
Thanks.

wrap the container in a dummy p element tag and you will get the container HTML also
var old_code_text = $("#template_invoice").wrap("<p/>").parent().html()
console.log("old text ="+old_code_text);

Related

How to append an html element from a string?

Hi,
I have a code like this, first my fixed html which is the container:
<div id="messages"></div>
then the javascript that generates its contents:
var post = `<div id="${userid}">${content}</div>`;
var item = document.createElement('div');
item.innerHTML = post;
messages.appendChild(item);
the problem with this is that it wrapps each post in a div which I dont need. This should be the output
<div id="messages">
<div id="user45">some content</div>
<div id="user46">more content</div>
</div>
how can I append the content of the string directly to the container without the wrapper?
Thank you.
You can use insertAdjacentHTML:
messages.insertAdjacentHTML('beforeend', post)

Get Html Code, replace parts and store in variable as string without changing the DOM Element

i have a DOM Element
<div class="list-item">
<div class="name"></div>
<div class="id" data-id=""></div>
Link
</div>
I want to get the HTML like $('.list-item').html();
Then i want to fill parts like data-attributes and content with own variables so i can get for example this:
<div class="list-item">
<div class="name">NAME CONTENT</div>
<div class="id" data-id="123456">CONTENT</div>
Link
</div>
Then i want to store that as string in a varibale like
var htmlCode = '<div class="list-item">.....';
The tricky part here is to do that all in Javascript without changing the DOM Element. I hope for help. Thanks!
You can use .clone() to clone your div and then use .attr() to change attr from id class .
Demo Code :
var htmls = $(".list-item").clone()
$(htmls).find(".id").attr('data-id', 'somehting');
console.log($(htmls).html()) //store in variable..
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list-item">
<div class="name"></div>
<div class="id" data-id=""></div>
Link
</div>
You can use this
<script>
var html = $('.list-item').html();
console.log(html);
var list = $('<li></li>')
$('.list-item').children().each(function(index,elem){
$(list).append($(elem).clone());
})
$(list).children().each(function(i,e) {
$(e).data("id","1234")
$(e).html("ll");
})
console.log($(list).children());
</script>
Thank you all. With your help i got this solution:
var $temp = $('.list-item').html();
var $code = temp.replace('data-id=""', 'data-id="1234"').replace('href=""', 'href="https://link.de"');
So $code is my varibale wich stores the html as string without changing the DOM Element :)

getElementByID for Dynamically generated ID Elements

I am having an issue with getting the value of an ID element of the item that is dynamically generated from the data obtained from the database. I have a query SELECT ItemID, ItemName, ItemImageName FROM Items. Than I have the following code that will generate ID for each <div> for all rows returned from the database by concatenating the value of ItemID to each ID name.
for ($i=0; $i <$numrows; $i++) {
$stmt->fetch()
<div> <img class="itemImage" id="Image" .$ItemID src=/images/itemImage . $itemID> $ItemID </div>
<div id= "ItemID" .$ItemID> $ItemID </div>
<div id= "ItemName" .$ItemID> $ItemName" </div>
}
This should return a similar result to this for an item with ItemID=002:
<div> <img class="itemImage" id=Image002 src=/images/Image002 > </div>
<div id= ItemID002> 002 </div>
<div id= ItemName002> SomeNameOfItem002" </div>
Then I want to be able to click an image with an ID=Image002 and I want to get a value of ItemID with the getElementById("ItemID").innerHTML. I have the following code:
var itemID = document.getElementById("ItemID").innerHTML;
$( ".itemImage" ).click(function() {
var itemID= document.getElementById("ItemID").innerHTML;
console.log(itemID);
This however returns itemID as undefined. Any help would be greatly appreciated!
<div> <img class="itemImage" id=Image001 src="/images/Image001"> </div>
<div id=ItemID001> 001 </div>
<div id=ItemName001> SomeNameOfItem001" </div>
<div> <img class="itemImage" id=Image002 src="/images/Image002"> </div>
<div id=ItemID002> 002 </div>
<div id=ItemName002> SomeNameOfItem002" </div>
<div> <img class="itemImage" id=Image003 src="/images/Image003"> </div>
<div id=ItemID003> 003 </div>
<div id=ItemName003> SomeNameOfItem003"> </div>
<script>
$(document).ready(function () {
$(".itemImage").click(function () {
var imgID = $(this).prop('id').replace("Image", "");
// you can directly use value imgID variable if its same. or you
//can use from ItemID inner html
var yourValue = $("#ItemID" + imgID).html();
alert(yourValue);
})
});
</script>
getElementById("ItemID").innerHTML returns undefined, because it is undefined. The correct id is ItemID002. You need to be able to tell which it is.
First, change your PHP to create HTML like this.
<div id="ItemID002" onclick="clicked(002)" />
Then, go to your Javascript and create this function.
function clicked(id){
var itemID= document.getElementById("ItemID"+id).innerHTML;
console.log(itemID);
}
Lastly, you're PHP creates <div id="ItemID"002>, you need to fix that by changing it from <div id= "ItemID" .$ItemID> $ItemID to <div id='ItemID.$itemId'>
EDIT: Also, I'd like to point out that in some places in your example, you forgot to use quotes when specifying the value of an attribute in HTML. I would recommend you fix that.
Good luck!
Alternatively you can achieve this by javascript only. So you don't need to change markup or PHP.
Here is a sample fiddle https://jsfiddle.net/L3bwfyve/
The key part is extraction of part of id of clicked element:
var itemIdPart = e.target.id.substr(5);
Be sure to check for nulls in e.target id etc...
Personally I would consider this solution a bit hacky... but you ask for javascrit, you get it ;-)

Javascript to get link text

My HTML looks like this:
<div class="col-md-2" id="myName1">
<p>
Get This Text
</p>
</div>
The question is how do I get the text "Get this Text"
Something like this, but getting that text which is wrapped in the p and a tags:
function () {
return document.getElementById('TextID');
}
You can search for the first p inside your myName1 element, then the first a within that.
var e = document.getElementById('myName1').
getElementsByTagName('p')[0].
getElementsByTagName('a')[0];
var theText = e.innerHTML;
console.log(theText);
// or, in sufficiently-modern browsers
e = document.querySelector('#myName1 p a');
theText = e.innerHTML;
console.log( theText );
<div class="col-md-2" id="myName1">
<p>
Get This Text
</p>
</div>
Try adding the following in your function:
return document.querySelector('#myName1 p a').innerHTML
Simply using document.getElementById('anchorID').text; assuming anchor has id of anchorID. The text property sets or returns the text content of a link.
EDIT 1 : If you are not able to add the ID, then you need to take long path by going to document.getElementByID and then reach to the element using the document.getElementsByTagName
var myAnchor = document.getElementById("myName1").getElementsByTagName('p')[0].getElementsByTagName('a')[0];
console.log(myAnchor.text);
<div class="col-md-2" id="myName1">
<p>
<a id="anchorID" href="/something/121212">Get This Text</a>
</p>
</div>
you can use the get element by tag name method, but it returns an array of results so you will have to consider that, in your example, this works...
var a=document.getElementById('myName1');
console.log(a.getElementsByTagName('p')[0].getElementsByTagName('a')[0].innerHTML);
<div class="col-md-2" id="myName1">
<p>
Get This Text
</p>
</div>
Check this code, you can use innerHtml attribute
<script>
function gettext()
{
return document.getElementById('link').innerHTML;
}
</script>
<div class="col-md-2" id="myName1">
<p>
Get This Text
</p>
</div>
<script>
alert(gettext());
</script>
Or if you are using JQuery
$("#myName1 p a").text();

rendering xml and html tags in a code snippet HTML

simply,how to render code snippet with <html> tags like this
<div id="container">
<div id="header_area"><tiles:insertAttribute name="header" /></div>
<div id="body_area"><tiles:insertAttribute name="body" /></div>
<div id="sidebar_area"><tiles:insertAttribute name="sidebar" /></div>
<div id="footer_area"><tiles:insertAttribute name="footer" /></div>
</div>
i found this code.but it adds endtag to all />
function encodePreElements() {
var pre = document.getElementsByTagName('pre');
for(var i = 0; i < pre.length; i++) {
var encoded = htmlEncode(pre[i].innerHTML);
pre[i].innerHTML = encoded;
}
};
function htmlEncode(value) {
var div = document.createElement('div');
var text = document.createTextNode(value);
div.appendChild(text);
return div.innerHTML;
}
so above code will be like this
<div id="container">
<div id="header_area"><tiles:insertattribute name="header"></tiles:insertattribute></div>
<div id="body_area"><tiles:insertattribute name="body"></tiles:insertattribute></div>
<div id="sidebar_area"><tiles:insertattribute name="sidebar"></tiles:insertattribute></div>
<div id="footer_area"><tiles:insertattribute name="footer"></tiles:insertattribute></div>
</div>
.innerHTML renders correctly in javascript alert. so how can i render code snippet like first? what is the easy way to do this process?
OK, so I assume that in your question, the first quoted block is embedded inside a <pre> element, like this:
<pre>
<div id="container">
...
</div>
</pre>
And you are trying to convert that so that it becomes:
<pre> <div ... </pre>
The problem is that when the page is loaded, the contents of <pre> is loaded into the DOM. When you get the value of pre[i].innerHTML, it returns you a value that accurately represents the DOM state, but is not the same as your original HTML.
If you want to preserve the exact HTML used in the page, you need to encode that HTML when you generate the page. By the time any JavaScript has access to the content, it's too late - the original HTML is gone, and all you have left is the DOM contents.

Categories