I know how to set an ALT tag on an <img> if I have the class or globally to all the images on the page, however how can I do it to a specific image that doesn't have an id or class? Can I use the parent DIV somehow to reference the image and add an alt tag?
<div id="table_processing">
<img src="processing_report.gif"> Loading Report List...
</div>
I'd recommend using document.querySelector(), which allows you to select the image using CSS (jQuery-like) selectors.
Like this:
var image = document.querySelector("#table_processing img");
and then you can set the alt attribute with:
image.alt = "Our New Alt Text";
or
image.setAttribute("alt", "our New Alt Text");
Here's a demo:
var image = document.querySelector("#table_processing img");
image.alt = "Our New Alt Text";
<div id="table_processing">
<img src="http://via.placeholder.com/350x150"> Loading Report List...
</div>
if you use jQuery, you could use the ID from the parent element like this:
$('#table_processing img').attr('alt', 'your text here');
This "css selector" will get all images inside the div with the id "table_processing" and sets the alt tag.
Pure/True/Real/Faster JavaScript Solution:
function setAlt()
{
var div = document.querySelector("#table-processing");
var image = div.querySelector("img");
image.setAttribute("alt", "something");
}
JQuery allows you to use valid css selector, so you can use this:
$('#table_processing img').attr('alt', <text>);
I hate to keep plugging jQuery, but here is a very good example of automating missing alt tags with generic info, this is something I do to patch for WCAG AA compliance until we can edit all the content.
$("img:not([alt])").attr({ alt: "your alt text", role: "presentation" });
$("iframe:not([title])").attr({ title: "your iframe title" });
This looks for images without alt attributes, adds it and adds the value "your alt text here" along with a role for screen readers, but you can remove that. IO. also do the same for iframes and embeds that may be third parties that are out of compliance.
Related
I'm expanding a site (menright.com) that displays about fifty years of photos. This link goes to the first photo page: (https://menright.com/pages/photoPages/photos-1967.php). Each photo is followed by a caption, and there is a button that allows the viewer to see a longer description that replaces the caption. The button isn't working here but allows you to see what I'm talking about.
To implement this I have an img (the button) inside of a p tag (the caption). Clicking the button substitutes the longer description drawn from the alt and the title in a second img (the picture) immediately above the caption.
I can't use IDs since there are many captions and pictures on each page.
Here is the HTML skeleton of the significant parts of the problem:
<img alt='long description' title='location image taken' />
<p class='the caption'> <img class='get long description button' /> </p>
I'm thinking I have to find the node of the target (the button), track its parent (the caption), and then get the alt and title from something like a previousSibling (the picture) and use the innerHTML of the parent (the caption) to display the long description.
Am I correct in this assumption, or is there another way to do this? And if this is the technique I need to use, how do I do it? I'm totally new to using nodes in my vanilla Javascript, and I don't want to add JSquery or other libraries to my pages.
This is my first post here, though I've used the site for years. Thanks for any help you might provide!
I'm thinking I have to find the node of the target (the button), track its parent (the caption), and then get the alt and title from something like a previousSibling (the picture) and use the innerHTML of the parent (the caption) to display the long description.
Am I correct in this assumption, or is there another way to do this?
If you stick to that structure, yes, that's what you'd do (probably previousElementSibling so you don't have to worry about intervening Text nodes), and setting textContent rather than innerHTML unless you want < and & in the text to be interpreted as HTML. You'd probably do it via event delegation on whatever container has all of these in it (body, if there's nothing nearer):
theContainer.addEventListener("click", event => {
const btn = event.target.closest(".get.long.description.button");
if (btn && theContainer.contains(btn)) {
const p = btn.parentElement;
const alt = p.previousElementSibling?.alt;
if (alt) {
p.textContent = alt; // `textContent` assuming you don't have tags
}
}
});
But if you can wrap all of that in an element:
<div class="wrapper">
<img alt='long description' title='location image taken' />
<p class='the caption'>
<img class='get long description button' />
</p>
</div>
...you can make it more robust:
theContainer.addEventListener("click", event => {
const wrapper = event.target.closest(".container");
if (wrapper && theContainer.contains(wrapper)) {
const p = wrapper.querySelector(".the.caption");
const alt = wrapper.querySelector(".location.image.taken")?.alt;
if (alt) {
p.textContent = alt; // `textContent` assuming you don't have tags
}
}
});
That doesn't rely on the exact relationship between the elements, just that they're all in the same container, so you can move them around as the page design evolves without changing your code.
Let's say I want to display the alt text for creek. How do I use the html DOM alt attribute in a function to target that specific image
You can just access it by its property
var altText = cr.alt
Heres some reference https://www.w3schools.com/jsref/prop_img_alt.asp
to check image alt: cr.alt
to return it: alert(cr.alt)
to change image alt: cr.alt = 'your new alt';
i want to make a website that allow users to input questions, and then the website will display some pictures related to user input
i tried to wrap the output in img src tag, however the output is simply a line of code instead of picture
<img src="path/reply.jpg" width="68" height="90" alt="reply">
how can i tell the website to recognize it as a picture and display it ?
is it possible to extend this function to embed youtube video etc. ?
==================================================================
Added some scripts below, i guess this is the code that limiting output as text only.....
function createRow(text) {
var $row = $('<li class="list-group-item"></li>');
$row.text(text);
$chatlog.append($row);
}
Update: i amended $row.text(text); to $row.html(text); , it can properly display html code now.
you can use ParentNode.append() function to append new image element to your html. (documentation here: https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/append)
Example:
var yourImage = document.createElement("img");
yourImage.src = "some/dynamic/source.jpg"
document.body.append(yourImage);
It is very simple, just try the following changes:
Add id attribute to your img tag:
<img src="path/reply.jpg" width="68" height="90" alt="reply" id="img1">
And in Jquery:
$(document).ready(function ()
{
$("#img1").attr({ "src": "img.jpg" });
});
Is there a way to add separate alternate text (such as "picture 1/2 not available") in case a picture fails to display? How can I change this code to allow that to happen?
(Sridhar's code)
<script type = "text/javascript">
function pic1()
{
document.getElementById("img").src = "picture 1 source";
}
function pic2()
{
document.getElementById("img").src ="picture 2 source";
}
</script>
<img src = "" id = "img"/> <input type="button" value="Show Picture
1" onclick="pic1()"/> <input type="button" value="Show Picture 2"
onclick="pic2()"/>
Is there a way to add separate alternate text (such as "picture 1/2
not available") in case a picture fails to display?
Yes, that is what the alt attribute is for - it is actually a required attribute for images anyway.
You can just set the alt tag of an image using .alt like so:
var image = document.getElementById("img");
image.src = "Image src here"
image.alt = "Image alt here - if image failed to render, you will see this!"
Assuming you have to do it by JavaScript. Most people simply just include it in the HTML itself:
<img src = "" id = "img" alt="Alternative text here!"/>
See more about the alt attribute here.
Edit: You could look into using onerror in regard to Derek's point:
"onerror allows for different alt text when an image is simply not found
rendered or when the image is not found"
Yes, there is a way. Use the onerror attribute with the error text or a path to an alternate image.
<img onerror="this.src='/path/to/alternate/img.jpg'" src="/your/img.jpg">
or
<img onerror="this.alt='picture 1/2 not available'" src="/your/img.jpg">
Edit: Of course, you should be using the (required) alt attribute on every image, as Zenith points out. Use of onerror assumes you wanted to show the user something different if the image could not be found instead of, say, the user is using a screen reader or has otherwise chosen to disable images. One alternative is to show the original alt text with the 'not available' message appended:
<img alt="picture 1/2" onerror="this.alt=this.alt+': not available'" src="/your/img.jpg">
Demo
Is there a way to get an image from an outer webpage with javascript code?
I'll explain:
I have a website, lets say www.one.com, and I want to show in this website's homepage an image that exists in another website, lets say www.two.co.il
Can I do it?
Try this:
var img = document.createElement("img");
img.src = "http://www.two.co.il/image.jpg";
document.body.appendChild(img);
A convenient thing is to create first a placeholder in your HTML:
<div id='externalImage'></div>
because it will not disrupt the function if the layout changes and allows precise placement.
As for the real question on how you put an image, assuming from the tags that you use Jquery:
$("#externalImage").html("<img src=\"http://put.url.here/image.jpg\" />");
if you want to insert it into the aforementioned placeholder. Otherwise to plainly add the image to the document you can append it to the documentd BODY or elsewhere using document.body.appendChild like in the other answers.
Yes.
var image = document.createElement('img');
image.setAttribute('src', 'http://www.two.co.il/foo.jpeg');
image.setAttribute('alt', 'something suitable');
document.body.appendChild(image);
So long as you aren't trying to get content from the other site into JS (you aren't, you are create an img element in the DOM, JS has no further involvement), you won't run into the Same Origin Policy.
or simply:
$("<img src='" + imgUrl + "' alt='" + altText + "'>").appendTo("body");
make a div and give id = "div1" with height and width
<div id='div1' height='100' width='100'></div>
$('#div1').css('background-image, 'http://www.two.co.il/urImage.jpg');
it is shortest way to apply image