简体   繁体   中英

jquery - how can I select element after '.first()' using?

How can I select html tag after using jquery function called .first() ?

HTML

<html>
  <head> </head>
  <body> 

       <div>
           <a>
              <img id="#hello">
           </a>
       </div>

       <div></div>
  </body>
 </html>

JS (JQuery)

var elemFirst = $(div).first();
var selectImg = elemFirst.$('img#hello');

// var selectImg = elemFirst.find('img'); <- It working but I want to select manual 

selectImg.addClass('some-css');

With Respect

Use find()

elemFirst.find('img#hello');

This will search for direct and nested elements with the provided selector.

Alternatively, you can do

$('div:first #hello')

or even just

$('#hello')

since you are using an id which should be unique.

You can use find() :

var selectImg = elemFirst.find('img#hello');

But you have an id of the image, so, you just can do this:

$('img#hello')

Because id is unique.

You can use $('child','parent') selector,

var elemFirst = $('div').first();
var selectImg = $('#hello',elemFirst);  //or just $('img',elemFirst);

Also, your id has a # , it should be just id="hello" .

If you need to keep this value in Id, use

var selectImg = $('img[id="#hello"]',elemFirst);

As in html the id be unique in html so striaghtly write

$("#\\#hello").addClass('some-css');

or

var selectImg = elemFirst.find('img[id="#hello"]');

Fiddle

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