At the moment I am trying to get value in src= of
<div class="page-break no-gaps">
<img id="image-0" src="https://foo.bar/image.jpg" class="wp-image" alt="Title">
</div>
with the following code:
getImageSrc(imageObj: Cheerio | undefined): string {
let image
image = imageObj?.attr('src')
console.log(image)
}
selector code:
chapterDetailsSelector = 'div.page-break > img'
However all I am getting is undefined
EDITED - add more context
View source html != what is fetched by cheerio
Seems like the image url is in attr('data-cfsrc') rather than attr('data') when fetched with cheerio
Related
I have multiple image paths saved into the database in the same column. The image is saved in this sample in the database:
Two images are not uploaded every time (the highlighted is the multiple image upload example separated by comma). I am using Nodejs and am getting the image data with foreach on the ejs side (data is the output of the select statement on the index.ejs side
index.js
router.get('/homes', function (req, res, next) {
db.query("SELECT * FROM stocks", function (err, rs) {
if (err) {
console.log(err);
}
else {
res.render('homes', {data:rs})
}
});
});
<% data.forEach(function(item) { %>
<input type="hidden" id="desc" value="<%= item.image %>" />
<img id="pic1" class="pic-1" src = "" alt="image" >
<% }); %>
item.image value (input string you are getting from $('#desc').val()). It is just string format of the image path as the loop occurs.
MyImage-1591506118979.png
MyImage-1591507932201.jpg
photos-1591548210637.jpg,photos-1591548210640.png
MyImage-1591494888039.png
MyImage-1591505437596.jpg
MyImage-1591084895899.jpg
MyImage-1591085173153.jpg
MyImage-1590905192772.JPG
I am saving the image on my localhost server. I am doing the split and wanting to append the src in the script tag with the code below:
<script>
var desc = $('#desc').val();
var temp = new Array();
temp = desc.split(",");
var container = document.getElementById("container");
temp.forEach(function (imagepath) {
var img = document.createElement("img");
img.className = "class";
img.src = imagepath;
// div.innerText = text;
img.classList.add("li-added");
container.append(img);
});
document.getElementById("pic1").src= "/" + text;
</script>
I use the same format for split text and it works, but am not sure what am getting wrong in the image part. I will appreciate any assistance or any other way to achieve this. Thanks.
I still don't know exactly what you intend to do. However, I tried to tidy up your code. In the HTML I got rid of the non-unique IDs by replacing them with class attributes.
In your JavaScript code I replaced the lengthy vanilla-JavaScript expressions by suitable jquery expressions and avoided some (temporary) variables altogether. The following is valid HTML and working JavaScript but might not be what you intended:
// var desc = $('#desc').val();
var data=[{image:"MyImage-1591506118979.png"},
{image:"MyImage-1591507932201.jpg"},
{image:"photos-1591548210637.jpg,photos-1591548210640.png"},
{image:"MyImage-1591494888039.png"},
{image:"MyImage-1591505437596.jpg"},
{image:"MyImage-1591084895899.jpg"},
{image:"MyImage-1591085173153.jpg"},
{image:"MyImage-1590905192772.JPG"}];
$("#container").html(data.map(item=>
`<input type="text" class="desc" value="${item.image}" /><br>`
+ item.image.split(',').map(pth=>`<img class="pic1" src ="${pth}" alt="${pth}"><br>`)).join(''));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container"></div>
Image loads correctly in HTML, but not when appended through jQuery.
The project is set up through webpack and images are loaded through file-loader. The code works correctly when directly typed into HTML however, it doesnt work when I attempt to load it through jQuery.
For HTML :
<img src = {require('../images/icon1.png')} className = 'studentIcon' />
For jQuery :
$("#students").append(
$("<div class = 'row'>").append(
$("<div class = 'col-xs-4'>").append(
"<img src = {require('../images/icon1.png')} />"
)
)
)
In HTML the jQuery appended images shows up as:
<img src="{require('../images/icon1.png')}">
with Console error:
icon1.png')%7D:1 GET http://localhost:8080/%7Brequire('../images/icon1.png')%7D 404 (Not Found)
When directly inserted into HTML the images shows correctly, however I have a large number of images which I want to directly attach to some generated code.
You don't need to "nest" many .append() methods like this.
But what you definitely have to do is to concatenate the string (+ sign) with your templating (which runs first), else it's just characters that are part of the string as is.
Here is what you want:
$("#students").append("<div class = 'col-xs-4'><img src = "+{require('../images/icon1.png')}+" /></div>");
And a more "visual/readable" way for the same:
$("#students")
.append("<div class = 'col-xs-4'>"+
"<img src = "+{require('../images/icon1.png')}+" />"+
"</div>");
Would advise the following.
$(function() {
var students = $("#students");
var row = $("<div>", {
class: "row"
}).appendTo(students);
var col = $("<div>", {
class: "col-xs-4"
}).appendTo(row);
$("<img>", {
src: "../images/icon1.png"
}).appendTo(col);
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="students">
</div>
This jQuery creates the various HTML Elements as jQuery OIbjects, appends them as needed, and adds them to the DOM. For the Image Source, it is a relative path to the location on the web server.
Hope that helps.
i'm implementing this tenor API into my Site....the thing is that with this function I retrieve a single value single gif...How do I foreach() all of them?
How would need to be the html structure and the javascript loop
JAVASCRIPT/ JSON
function grab_data(anon_id)
{
// set the apikey and limit
var apikey = "*************";
var lmt = 8;
.....
// callback for trending top 10 GIFs
function tenorCallback_trending(responsetext)
{
// parse the json response
var response_objects = JSON.parse(responsetext);
top_10_gifs = response_objects["results"];
// load the GIFs -- for our example we will load the first GIFs preview size (nanogif) and share size (tinygif)
document.getElementById("preview_gif").src = top_10_gifs[1]["media"][0]["nanogif"]["url"];
document.getElementById("share_gif").src = top_10_gifs[6]["media"][0]["tinygif"]["url"];
return;
}
I would have this top_10_gifs variable loaded of content...how do I foreach it?
HTML
<h2 class="title">GIF loaded - preview image</h2>
<div class="container">
<img id="preview_gif" src="" alt="" style="">
</div>
<h2 class="title">GIF loaded - share image</h2>
<div class="container">
<img id="share_gif" src="" alt="" style="">
</div>
Depends on what exactly you're trying to do (which you haven't explained), but something like
response_objects.results.forEach((gifObj, i) => {
if (i >= 8) return;
// do something with each gifObj
document.querySelector('.container')
.appendChild(document.createElement('img'))
.src = gifObj.media[0].tinygif.url;
});
to iterate over all of them.
I'm trying to display remote images in a FireFox add-on panel, but the src attributes are being converted from something like this:
http://example.com/image.jpg
to something like this:
resource://addon_name/data/%22http://example.com/image.jpg%22
I can't figure out if I'm breaking a security policy or not.
In my add-on script (index.js) I'm retrieving image URLs using the sdk/request API and passing them to my content script (data/my-panel.js). My data/my-panel.js file is creating DOM elements in my panel file (data/popup.html) – including images – using the URLs passed from index.js. Here are the relevant bits of code:
index.js
var Request = require("sdk/request").Request;
var panel = require("sdk/panel").Panel({
width: 500,
height: 500,
contentURL: "./popup.html",
contentScriptFile: "./my-panel.js"
});
Request({
url: url,
onComplete: function(response) {
// Get the JSON data.
json = response.json;
// Launch the popup/panel.
panel.show();
panel.port.emit("sendJSON", json);
}
}).get();
data/my-panel.js
var title;
var desc;
var list;
var titleTextNode;
var descTextNode;
self.port.on("sendJSON", function(json) {
json.docs.forEach(function(items) {
title = JSON.stringify(items.sourceResource.title);
desc = JSON.stringify(items.sourceResource.description);
img = JSON.stringify(items.object);
console.log(img);
var node = document.createElement("li"); // Create a <li> node
var imgTag = document.createElement("img"); // Create a <img> node
imgTag.setAttribute('src', img);
imgTag.setAttribute('alt', desc);
imgTag.style.width= '25px';
titleTextNode = document.createTextNode(title);
descTextNode = document.createTextNode(desc);
node.appendChild(titleTextNode); // Append the text to <li>
node.appendChild(descTextNode); // Append the text to <li>
document.getElementById("myList").appendChild(node); // Append <li> to <ul> with id="myList"
document.getElementById("myImgs").appendChild(imgTag);
});
});
The console.log(img) line is displaying the URLs correctly, but not in popup.html...
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<ul id="myList"></ul>
<p id="myImgs"></p>
</body>
</html>
How can I make the images' src attributes point directly to the remote URLs?
Thanks!
I figured out what I was doing wrong. Using JSON.stringify() on the img URL was adding double quotes around it. Removing it fixed the images:
img = items.object;
I'm not so sure about SDK permissions, but as a last resort you can turn the remote url into a resource URI like this -
var res = Services.io.getProtocolHandler("resource").QueryInterface(Ci.nsIResProtocolHandler);
res.setSubstitution("rawr", Services.io.newURI('http://www.bing.com/',null,null));
// now try navigating to resource://rawr it will load bing
Then you can load resource://rawr and it should work.
I know how to append a image to a known tag. e.g.
//html
<div class="ImageContainer"></div>
//JS
var image = new Image;
image.src = '/Public/Images/image.png';
image.appendTo($('.ImageContainer'));
but how to find a certain tag(the figure tag here) and append the image?
I could locate the figure tag with '.find()':
var ImageContainer = $('<div><figure></figure></div>').
console.log(ImageContainer.find('figure').html());
but failed to append the image to it:
image.appendTo(ImageContainer.find('figure')); //doesn't work
If you have an image element with an id you can select it like so:
var $image = '<img src="/Public/Images/image.png" />';
Then so find the figure elemnt:
$(ImageContainer).find('figure').append($image);
Try below code.
1) Stored image url in variable name $img.
2) Find the div using class name 'image' ($('.image'))
3) Appended image to div
HTML
<div class="image"> </div>
JS
var $img = '<img src="https://skypeblogs.files.wordpress.com/2013/05/skype-button.png"/>';
$('.image').append($img);
JSFIDDLE DEMO
if you are using jquery, you can just do
var htmlString = '<div><figure><img src="some image src" /></figure></div>';
$('#ImageContainer').html(htmlString);
but if you are wanting to insert the div/figure and image separately, then you'd be best giving it some sort of identifier, i.e.
var htmlString = '<div><figure id="myFig"></figure></div>';
$('#ImageContainer').html(htmlString);
$('#myFig').html('<img src="" />');