Get element from HTML object javascript - javascript

I have a HTML String and I want to get img element and initialize it.
var discountItem = '<li class="sidebar-brand" style="font-weight: bold; color: #9999 class="col-item">' +
'<div class="post-img-content">' +
'<img src=" " class="img-responsive" id="mimo" />'+
'<span class="post-title">'+
'<b>Perfumes</b><br>'+
'<b>Clássico</b>'+
'</span>'+
'<span class="round-tag">-15%</span>'+
'</div>'+
'</li>';
var k = app.clone(discountItem);
var df = document.createDocumentFragment();
// create a placeholder node to hold the innerHTML
var el = document.createElement('body');
el.innerHTML = k;
// append to the document fragment
df.appendChild(el);
// execute .getElementById
console.log(df.getElementByClassName('img-responsive');
view += k;
clone : function(obj){
try{
var copy = JSON.parse(JSON.stringify(obj));
} catch(ex){
console.log("you are using an old navigator");
}
return copy;
}
I tried this but it doesn't work.
My goal is to initialize the src of the image.
Could someone help me ?

If you're trying to find the img element, you can do a lot less work: Just create a body, append that HTML to it, and use querySelector:
var discountItem = '<li class="sidebar-brand" style="font-weight: bold; color: #9999 class="col-item">' +
'<div class="post-img-content">' +
'<img src=" " class="img-responsive" id="mimo" />'+
'<span class="post-title">'+
'<b>Perfumes</b><br>'+
'<b>Clássico</b>'+
'</span>'+
'<span class="round-tag">-15%</span>'+
'</div>'+
'</li>';
var body = document.createElement("body");
body.innerHTML = discountItem;
var img = body.querySelector(".img-responsive");
img.src = "source path here";

Related

Create menu by removing duplicates from JSON data

Build dynamic menu from multiple metadata files
I have a JavaScript loop that displays the images from an NFT collection and uses the class names to create a filter. Currently the filter menu is hard-coded, but I would like to build it dynamically from the metadata.
var loopFunction = function(dataIsLoading) { // the loop
let itemID = "";
var itemSource = "Azuki";
var itemURI = "https://ikzttp.mypinata.cloud/ipfs/QmQFkLSQysj94s5GvTHPyzTxrawwtjgiiYS2TBLgrvw8CW/"
for (let i = 0; i < 100; i++) {
itemID += [i];
$.getJSON(itemURI+i, function(data) {
// alert(data.name);
var eachItem = "";
var itemName = data.name;
var traits = data.attributes;
var classes = "";
var traitList = "";
$.each(data.attributes,function(index,entry) { // k (key), v (value) / i (index), e (entry)
var str = entry.value;
str = str.replace(/ /g, '');
classes += '' + entry.trait_type + '' + str + ' ';
traitList += '<span class="item-trait-type">' + entry.trait_type + ':</span> ' + str + '<br />';
});
eachItem += '<div class="cstm-grid-item cstm-width-1-2 cstm-width-large-1-3 cstm-width-x-large-1-4 ' +classes+'" id="'+i+'">';
eachItem += '<div class="img-placeholder">';
eachItem += '<img class="lazy" data-src="https://ikzttp.mypinata.cloud/ipfs/QmYDvPAXtiJg7s8JdRBSLWdgSphQdac8j1YuQNNxcGE1hg/'+i+'.png" width="100%" height="auto" />';
eachItem += '</div>';
eachItem += '<span class="item-title">'+itemName+'</span>';
eachItem += '<p class="item-traits">'
eachItem += traitList;
eachItem += '</p>'
eachItem += '</div>';
$('.cstm-grid').append(eachItem);
});
}
};
I have all of the data, but building the menu is difficult to do dynamically without the the menu having duplicate values. I just need the single base category (trait type) and the single values for that trait type. The final output should look something like:
<ul>
<li>
<h2>Trait Type 1</h2><!-- the category -->
<ul>
<li>red</li><!-- the value -->
<li>blue</li><!-- the value -->
</ul>
</li>
<li>
<h2>Trait Type 2</h2><!-- the category -->
<ul>
<li>sunglasses</li><!-- the value -->
<li>hat</li><!-- the value -->
</ul>
</li>
</ul>

print array of object in javascript and print in html tags

i am using storelocater.js for multiple location in google map and show the information according to the location with image. i can show only one image but i want to show multiple images inside the information panel. link this
Here is my code
var panelDiv = document.getElementById('panel');
storeLocator.Panel.NO_STORES_IN_VIEW_HTML_ = '<li class="no-stores">The nearest outlet:</li>';
var Store = storeLocator.Store;
Store.prototype.generateFieldsHTML_ = function(fields) {
var html = '';
html += '<div class="store-data">';
if(this.props_['title']){
html += '<div class="title"><div class="img-list clearfix">' +
for (var i = 0; i <= this.props_[images].length; i++) {
console.log(this.props_[images[i]]);
// <img src=' + this.props_['images'] + '>
}
+ '</div></div>'
}
html += '</div>';
return html;
}
var data = new storeLocator.StaticDataFeed;
data.setStores([
new storeLocator.Store('store02', new google.maps.LatLng(27.67663,85.31093), null, {images: ["img/thapathalil.jpg","img/thapathalil.jpg","img/thapathalil.jpg"]})
]);
and it shows:
Uncaught SyntaxError: Unexpected token for...
how can i solve this?? how can i fetch location inside of "images"
THANKS in advance
Actually you got Uncaught SyntaxError: Unexpected token for... because you used the for..loop in the string concatenation statement, directly after the + sign.
Change this code :
html += '<div class="title"><div class="img-list clearfix">' +
for (var i = 0; i <= this.props_[images].length; i++) {
console.log(this.props_[images[i]]);
// <img src=' + this.props_['images'] + '>
}
+ '</div></div>'
To the following:
html += '<div class="title"><div class="img-list clearfix">';
for (var i = 0; i <= this.props_['images'].length; i++) {
console.log(this.props_['images'][i]);
html += '<img src=' + this.props_['images'][i] + '>';
}
html += '</div></div>'
Note:
You should separate the concatenation of strings to the html
variable and the for loop logic, using html += instead of just using concatenation with + sign on multiple lines.
Make sure to wrap the properties names between two '' while accessing your objects, like in this.props_[images] where it should be this.props_['images'] and in this.props_[images[i]] where it should be this.props_['images'][i].
And the first 2 lines of your html variable decalaration and the concatenation, var html = ''; html += '<div class="store-data">'; can be shortened to just var html = '<div class="store-data">';.
I think there is a typo. Change this:
console.log(this.props_[images[i]])
to
console.log(this.props_['images'][i])
And you should use
i < this.props_['images'].length
So try this:
for (var i = 0; i < this.props_['images'].length; i++) {
console.log(this.props_['images'][i]);
}

Dynamically creating image link Jquery or vanilla Javascript

I am trying to figure out how to dynamically create a image with caption below it. I would like it so that when a user clicks the image or caption it redirects to a different page. I have a feeling what I am doing is wrong on many levels.
function createFrame(data){
// <div><img src=""><div></div></img></div>
var div = document.createElement('div');
var a = document.createElement('a');
var img = document.createElement('img');
a = a.innerHTML(img);
div.innerHTML(a);
return div;
});
Using .append() in jquery, you can append the image tags in the desired div.
$("#btn").click(function(){
$("#imgDiv").append('<img src="" alt="Image"/>')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">Create Image Link</button>
<div id="imgDiv">
</div>
Following your idea of creat that you want, i did the following:
function createFrame(data){
// <div><img src=""><div></div></img></div>
var div = document.createElement('div');
var a = document.createElement('a');
a.href = 'your-href-link';
var img = document.createElement('img');
img.src = 'your-src-link';
var div_caption = document.createElement('div');
a.appenchild(img);
a.appenchild(div_caption);
div.appenchild(a);
});
There are several ways to do it with pure JS or with frameworks (jquery..).
Pure js :
Level 1 simple
function createFrame(src){
return "<div>"+
"<a href='"+src+"' target='_blank'>"+
"<img src='"+src+"' alt='demo'/>"+
"</a>"+
"</div>";
}
document.getElementById("demo").innerHTML = createFrame("http://lorempixel.com/100/100");
<div id="demo"></div>
<br/>
2nd Level
document.getElementById("demo").innerHTML = createFrame("http://lorempixel.com/100/100");
function createFrame(src=false, divID = false, link=false, aID=false, imgID=false, openToNewTab = false){
$html = "";
$html += "<div ";
if(divID !== false) $html += "id = '"+divID+"' ";
$html += ">";
$html += " <a href='";
$html += (link !== false)? link+"' ":"#' ";
$html += (openToNewTab !== false)? " target='_blank'":"";
$html += ">";
$html += "<img src='"+src+"' ";
$html += imgID? " id='"+imgID+"'":"";
$html += " /></a></div>";
return $html;
}
<div id="demo"></div>
3rd Level
var html = createFrame(
{"src":"http:lorempixel.com/100/100", "id":"img"},// img attributes
{"href":"http:lorempixel.com/100/100", "class":"caption", "target":"_blank"}, // a attributes
{"class":"imgContainer"}//div
);
document.getElementById("demo").innerHTML = html;
function createFrame(img={}, a={}, div={}){
var html = "";
html = TagGenerator("img", img, "",true);
html = TagGenerator("a", a, html);
html = TagGenerator("div", div, html);
return html;
}
function TagGenerator(tagname, attr=[], html="", endAbleTag=false){
var tag = "<"+tagname+" ", i;
for (i in attr)
tag += i+"='"+attr[i]+"' ";
if(!endAbleTag) tag += ">"+html+" </"+tagname+">";
else tag += "/>";
return tag;
}
<div id="demo"></div>

Images and links are not working when they are values of json object properties

I don't know what is happening, but both my images and links are not working, even after declaring globally!?
if I write the src directly into src then everything seems fine , even alert pops the same url and img src! need help guys!
var combo0;
var combo1;
var combo2;
var combo3;
var random;
var images=["../IMAGES/park.jpg","../IMAGES/palace.jpg","../IMAGES/oriental.jpg"]
var weburls=["https://www.royalplaza.com.hk","https://www.caesars.com","http://www.venetianmacao.com/"]
function gethotel(){ // a= check-in b=check-out and c=no-of-rooms
var arraysofobjects=[
combo0=[
],
combo1=[
{hotelname:"The Royal Plaza",purl:"images[0]",rflag:"",weburl:"weburls[0]",description:"Locate"
,price:"HKD 1200"},
],
combo2=[
{hotelname:"The Royal Plaza",purl:"images[0]",rflag:"",weburl:"weburls[0]",description:"Located drive away."
,price:"HKD 1200"},
{hotelname:"Caesars Palace",purl:"images[1]",rflag:"",weburl:"weburls[1]",description:"Built in 1903, the treatments"
,price:"HKD 1900"}
],
combo3=[
{hotelname:"The Royal Plaza",purl:"images[0]",rflag:"",weburl:"weburls[0]",description:"Located in less ."
,price:"HKD 1200"},
{hotelname:"Caesars Palace",purl:"images[1]",rflag:"",weburl:"weburls[1]",description:"Built in 1903, tatments"
,price:"HKD 1900"},
{hotelname:"The Venetian Hotel",purl:"images[2]",rflag:"",weburl:"weburls[2]",description:"The Vor area."
,price:"HKD 2200"}
]
]
random=Math.floor((Math.random() * 4));
return arraysofobjects[random];
}
var object=gethotel();
for(var i=0; i<random;++i) {
var heading = '<h2>' + object[i].hotelname + '</h2>';
var description = '<p>' + object[i].description + '</p>';
var priceho='<h4>' + object[i].price + '</h4>';
//web url
var a = document.createElement('a');
var linkText = document.createTextNode("Offical website");
a.appendChild(linkText);
a.title = "official website";
a.href = object[i].weburl;
var hotel = '<img src="object[i].purl">' + '<div>'+ heading + description + priceho + '<a target="_blank" href=object[i].weburl>Official website</a>' +'</div>';
var str="Details";
var link=this.str.link("room.html");
document.getElementById("hotels").innerHTML+=hotel + link;
}
It looks like is may be because your weburl:"weburls[0]" property value has quotes around it. Try it like: weburl:weburls[0].
I assume that you have an array elsewhere in your code named weburls, and the above property is supposed to be setting the weburl property equal to the value of the 0-indexed item in weburls.
With the quotes it means after this line a.href = object[i].weburl;, a.href is literally equal to "weburls[0]". You should be able to perform an inspection on the DOM to confirm this.
Update
The code in the for loop seems that it could be replaced with this:
var heading = '<h2>' + object[i].hotelname + '</h2>';
var description = '<p>' + object[i].description + '</p>';
var priceho='<h4>' + object[i].price + '</h4>';
var hotel =
'<img src="' + object[i].purl + '" />' +
'<div>' + heading + description + priceho +
'<a target="_blank" href="' + object[i].weburl + '">Official website</a>' +
'</div>';
document.getElementById("hotels").innerHTML += hotel;

JSON date not showing in HTML

I have a problem with JSON data: I want make news feed via JSON URL, but the information not showing in HTML.
$(function() {
var entries = [];
var dmJSON = "http://www.stellarbiotechnologies.com/media/press-releases/json";
$.getJSON( dmJSON, function(data) {
var html = '<div class="panel-body"><h3 class="lead">${title}</h3>';
html += '<time datetime="${published}">';
html += '<span class="glyphicon glyphicon-time"></span> ';
html += '<span class="month">${monthName}</span> ';
html += '<span class="day">${day}</span>, ';
html += '<span class="year">${year}</span></time></div>';
$('#ticker').html
},
<div id="ticker"></div>
You could do something like this:
<script>
$(document).ready(function() {
var dmJSON = "http://www.stellarbiotechnologies.com/media/press-releases/json";
$.getJSON( dmJSON, function(data) {
var html = '';
// loop through all the news items, and append the
// title and published date to the html variable.
for(var i = 0; i < data.news.length; i++){
html += '<div>';
html += data.news[i].title
html += '<br>';
html += data.news[i].published
html += '</div>';
}
// append all the html variable to the ticker div.
$("#ticker").append(html);
});
});
</script>
This will loop through the news node, and get the title and the published date and then append them to the page (an element with the id of ticker.

Categories