The title already tell's a little bit. I'm getting a list of documents with links and images like this:
<img class="Thumbnail" src="sourcetothepdfimage.png" id="/path/pdf.png"/>
The only two things that may differ are src and id. What I try to reach now is to replace the image src depending on its ID. The ID may be /path/pdf.png or /path/word.png or something completely different (which I don't know yet).
What would be the recommended way to achieve this? I have three different images for the replacement (one for PDF, one for word files and one generic for all other unknown file types).
I think document.getElementByID doesn't make that much sense because I only know two fix IDs. With this I can change the src for PDF and DOCX but not for any other, right?
So document.getElementsByClassName would be the targeted solution, but how can I iterate through all five or more listed elements with the class "Thumbnail"?
I'm barely new to the Dev world and like to learn it.
It's simple using jQuery.
// get all img's using class selector
// and use `attr()` method with callback which iterate internally
// within the callback return the id( within callback this refers to the current element DOM object)
$('.Thumbnail').attr('src',function(){
return this.id
})
<img class="Thumbnail" src="sourcetothepdfimage.png" id="/path/pdf.png"/>
Try (no jquery)
[...document.querySelectorAll('.Thumbnail')].map(img=> img.src=img.id);
console.log([...document.querySelectorAll('img')]);
<img class="Thumbnail" src="sourcetothepdfimage.png" id="/path/pdf.png"/>
<img class="Thumbnail" src="sourcetothesomimage.png" id="/path/pdf2.png"/>
<img class="Thumbnail" src="sourcetothedocimage.png" id="/path/doc.docx"/>
Related
I'm trying to replace the image source, but only if the image corresponds to the existing class "overview-icon--downtime". Then there's another class, "overview-icon--degraded", which I want to replace it with (or simply putting an image address, which might prove easier).
To be replaced:
<div class="page__overview">
<img class="page__overview-icon overview-icon--downtime" src="downtime_large.png">
</div>
To be replaced with:
<div class="page__overview">
<img class="page__overview-icon page__overview-icon--degraded" src="degraded_large.png">
</div>
I was thinking of this, but I'm not sure I'm heading in the right direction.
document.querySelector(".page__overview-icon overview-icon--downtime").setAttribute("img", "page__overview-icon page__overview-icon--degraded");
The image loads with the page, so I'll also need to use the AJAX at the end.
Any ideas here please? Thanks a lot in advance! :3
You are heading in the right direction.
Attributes are the things inside of the tags. In this instance, "class" and "src" are attributes of the img element.
document.querySelector will select the img element, you then need to call setAttribute('class', new class value), and setAttribute('src', new src value)
I want to display multiple images starting with _id value in ng-repeat in the view like this .
<div ng-repeat="property in properties">
<img src="uploads/#{{property._id}}.jpg" alt="Smiley face" width="42" height="42"/>
</div>
now consider this
if
_id = 1
there are multiple images in the uploads like this
/uploads/
1a.jpg
1b.jpg
1zaz.jpg
1io.jpg
i want to show all those images against every property,.
Help me for this.
now consider this if
_id = 1
there are multiple images in the uploads like this
/uploads/
1a.jpg
1b.jpg
1zaz.jpg
1io.jpg
i want to show all those images against every property
The only way you can do that is if you know in advance that the names have a, b, zaz, and io appended to them. You can't use a wildcard to say "repeat this img element for any files that happen to exist."
So as part of your build process or similar, you'll need to identify the actual images that exist, and then cover all of them within the ng-repeat. The details of how you do that are obviously going to be highly specific to your environment, so we can't give you those specifics.
Just want to ask what is recommended to use with Angular, standard html src or Angular [src]? And why?
Edit: I have following code in my html component:
<img class="logo" src="../app/media/appLogo.png">
It is fine? If not, how should I change it to work together with [src]?
Edit2: Is there any other, better way to do it, instead of plain html src? Or this is the best solution actually?
[...]="..." is for object binding ...="{{...}}" is for binding with string interpolation. If you want to bind a string it doesn't matter what you use. If you want to bind an object or array value you need to use `[...]="...". Besides that it's entirely up to you.
<img class="logo" src="../app/media/appLogo.png">
Is not related to Angular2 at all, thats just plain HTML (no [] and no {{}}). If you add [] around src, then Angular will treat ../app/media/appLogo.png as an expression, which it clearly isn't.
When DomSanitizer is used [src]="..." is mandatory because the value no longer is a string, but an object and using {{}} would stringify it in an invalid way.
Using regular src sets the Attribute where setting [src] sets the property. Considering that for an image (I assume you're talking about an image but you don't say) the src attribute is used to set the corresponding property they will both work.
There is one big reason to use [src] though. Browsers tend to start downloading whatever you put in the src attribute while parsing the html. So lets say you do this:
<img src="{{myImgSrc}}"/>
The browsers will often immediately start downloading {{myImgSrc}}, which will lead to a 404 in the console. Using the following is therefor slightly better:
<img [src]="myImgSrc"/>
If you have static anchor link, then go ahead with
<img class="logo" src="../app/media/appLogo.png">
When binding from the component, then either of the below will work.
<img class="logo" [src]="image_src">
<img class="logo" src="{{ image_src }}">
In component.ts
image_src: string = '../app/media/appLogo.png';
I have a web site with an image slider. I keep the some of the image tags empty as the images load on when slide comes into view for faster page load. The image tags defined as follows:
<img data-src="img/portfolio-desktop1-small.png" src="" alt=""/>
What I'm doing is on slide function I change the src to data-src with jQuery animation. The slider works great. My problem is when I try to validate it in w3c validation tool it gives the following error:
Line 131, Column 179: Bad value for attribute src on element img: Must be non-empty.
...data-src="img/portfolio-desktop1-small.jpg" src="" alt=""/>
Syntax of URL:
Any URL. For example: /hello, #canvas, or http://example.org/. > Characters should be represented in NFC and spaces should be escaped as %20.
Is there anyway to fix this without altering the JavaScript or CSS? If I leave it like this what can be the possible harmful outcomes of this matter?
Set the image src attribute to #:
<img data-src="img/portfolio-desktop1-small.png"
src="#" alt="Thumbnail">
The HTML passes the W3C validator just fine, and modern browsers know not to try to load the non-existent image.*
For contrast, using a src value that references a non-existent file results in an unnecessary HTTP request and an error:
<img data-src="img/portfolio-desktop1-small.png"
src="bogus.png" alt="Thumbnail">
Failed to load resource: The requested URL was not found on this server.
*Note: I've read conflicting information on how browsers handle the #. If anyone has definitive information, please add a comment.
Also see related answer by sideshowbarker about the action attribute: https://stackoverflow.com/a/32491636
Update: November 2022
It seems the src="#" trick used to be a decent workaround but it's no longer a good idea to send that to the browser.
So, I created a build tool to convert occurrences of src="#" in source HTML to inline data URLs of a tiny invisible one pixel SVG appropriate for the browser.
Build tool img-src-placeholder:
https://github.com/center-key/img-src-placeholder (MIT License)
The interesting bits are:
const onePixelSvg =
'<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"></svg>';
const dataImage = 'data:image/svg+xml;base64,' +
Buffer.from(onePixelSvg).toString('base64');
html.replace(/src=["']?#["']?/gm, `src="${dataImage}"`);
The resulting HTML will have <img> tags like:
<img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxIiBoZWlnaHQ9IjEiPjwvc3ZnPg=="
alt=avatar>
The advantage of using a build tool is that:
Source remains uncluttered
HTML always validates
The inline data URL prevents the browser from making an unnecessary and invalid network request
What happens if you just remove the src attribute then add it on the fly when you need it. The src attribute isn't required. And in my opinion I wouldn't worry about what the w3c validation tool says anyway. As long as you test it in the necessary browsers and it works.
Update Jan 2021. The src="#" trick works now on the validator at https://www.w3.org/TR/html-media-capture/
If anyone still looking for the answer, the src="/" code resolves the w3c validator complains and doesn't produce additional request like the solution with the # character.
I've used a for loop to create a bunch of images with unique ids. They look something like this:
<img src="image.jpg" id="110021002" />
<img src="image.jpg" id="110021003" />
<img src="image.jpg" id="110031002" />
...
Later on in the code I want to select one of the images by ID and remove it. I tried the following:
var removeId = '110021002';
var img = document.getElementById(removeId);
img.parentNode.removeChild(img);
But I get the following error:
Cannot read property 'parentNode' of null
Not quite sure what's going on here. Is it because the images were created dynamically?
Your code works perfect: http://jsbin.com/zexoweyu/3/edit for the first time you remove an element, obvisouly on the second attempt the element is not there and it will throw the given error.
On the fiddle:
Click once, works
Click again, fails because the element with that ID is no longer there.
And yes, ids can start with numbers.
**Attribute ID** Specifies a unique id for the element. Naming rules:
Must contain at least one character
Must not contain any space characters
In HTML, all values are case-insensitive
You can't have IDs that start with a number. Try prefixing them with a letter.