简体   繁体   English

jQuery-如何在使用'.first()'之后选择元素?

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

How can I select html tag after using jquery function called .first() ? 使用名为.first() jquery函数后,如何选择html tag

HTML 的HTML

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

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

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

JS (JQuery) 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() 使用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. 因为您使用的ID应该是唯一的。

You can use find() : 您可以使用find()

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

But you have an id of the image, so, you just can do this: 但是您具有图像的id ,因此,您可以执行以下操作:

$('img#hello')

Because id is unique. 因为id是唯一的。

You can use $('child','parent') selector, 您可以使用$('child','parent')选择器,

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

Also, your id has a # , it should be just id="hello" . 另外,您的ID有一个# ,应该只是id="hello"

If you need to keep this value in Id, use 如果您需要将此值保留在ID中,请使用

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

As in html the id be unique in html so striaghtly write 就像在html中一样,id在html中是唯一的,因此可以写

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

or 要么

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

Fiddle 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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