From past questions I know you can set a new attr() to existing elements on the page such as an ID to the images on the page, but in my case I want to set an id to only the first image. The other 4 for example are left without this ID being added.
With the below code, it keeps adding the ID to all images on the page.
<script>
$( "img" ).attr( "id", "wp_featured_img" );
</script>
First img only.
asked Nov 7, 2014 at 23:19
wharfdale
7727 gold badges25 silver badges64 bronze badges
3 Answers 3
You can use the jQuery :first selector to achieve this. You code would look like this:
<script>
$( "img:first" ).attr( "id", "wp_featured_img" );
</script>
Hope this helps!
Sign up to request clarification or add additional context in comments.
3 Comments
wharfdale
Ah yep this works. Although just realised it now adds it to my logo because technically that is the first instance of 'img', is there a way to define the first 'img' within a particular div?
Jerome
If you have a container for all your images (say it has attribute
id="myImageContainer"), you can change your selector to become $( "#myImageContainer img:first" ).attr( "id", "wp_featured_img" );.wharfdale
Spot on, got it now. Thanks. Will accept in a few minutes when I can. To the others, thanks for your answers. All work although this response was simply the first so selecting this one.
Use the :first selector:
$( "img:first" ).attr( "id", "wp_featured_img" );
that selects the first matched img element.
answered Nov 7, 2014 at 23:22
Yair Nevet
13.1k17 gold badges71 silver badges111 bronze badges
Comments
answered Nov 7, 2014 at 23:22
Karthik Ganesan
4,2622 gold badges28 silver badges43 bronze badges
Comments
lang-js