0

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
0

3 Answers 3

2

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!

answered Nov 7, 2014 at 23:21
Sign up to request clarification or add additional context in comments.

3 Comments

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?
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" );.
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.
1

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

Comments

1

use

$( "img" ).first().attr( "id", "wp_featured_img" );

jsfiddle for the same

answered Nov 7, 2014 at 23:22

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.