简体   繁体   中英

Get src type of img or video tag (not extension)?

Say I have an image tag such as this:

<img src="smiley.gif" alt="Smiley face" height="42" width="42">

I know I can get the src by using myImageEl.src .

However, how do I get the type of the src ( .gif in this case)?

Basically, my end goal is to pass the file type to window.URL.createObjectUrl()

let src = imageEl.src;
let srcType = src.type; // Here I need to get the type
let videoFile = new Blob([src], {type: srcType});
let videoSrc = window.URL.createObjectURL(videoFile);
var imgSrc = 'image.jpeg';
var ext = imgSrc.replace(/^.*\./, '')

I am not very good with regex, but using regex to fetch the extension of the image or video is the a good way of accomplishing this task.

For precision sake you could compare ext with a predeifined set of array

imgTag = ['jpg', 'jpeg', 'gif', 'png'];
vidTag = ['mp4', '3gp']

then you can compare using a forEach loop

From your tags I noticed you want to access image source type from javascript, if so you can use following codes base on what attributes we have for that image element: for example if image element has id :

var imageElement = document.getElementById(id);
var imgsrc = imageElement.src;
var imgType = imgsrc.split('.').pop();

imgType will be the type of your image.

And if your image element doesn't have id, you can use document.getElementsByTagName("img") instead of document.getElementById(id) and code will look like this

var imageElement = document.getElementsByTagName("img");
var imgsrc = imageElement.src;
var imgType = imgsrc.split('.').pop();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM