[英]How to find a dom element inside another dom element?
我在ajax调用中将html返回给我:
$.ajax({
url: '/get-html',
dataType: 'html',
success: function(html) {
html = $(html);
....
在成功方法中,我希望在html var的容器div中找到img标签,并将其更改为alt标签。
如果我做:
html.find('img').attr('alt', 'new alt');
我们更新所有图像上的替代项。 如何只为容器div指定alt? 我已经试过了:
html.find('.container img').attr('alt', 'new alt');
但它不起作用。
仅供参考,这是ajax调用中返回的HTML的示例:
<div class="container">
<img src="" alt="PLEASE CHANGE THIS ALT">
</div>
<img src="" alt="LEAVE MY ALT ALONE">
<img src="" alt="LEAVE MY ALT ALONE">
尝试这个 -
var html = '<div class="container"><img src="" alt="PLEASE CHANGE THIS ALT"/></div><img src="" alt="LEAVE MY ALT ALONE"/><img src="" alt="LEAVE MY ALT ALONE"/>'; //Print Your html Code before changing alt attr. $('body').append(html); $('body').append('<hr/>'); html = $(html); //Check img inside .div and change attr html.children('.container img').each(function() { $(this).attr('alt', 'new alt'); //Log changed attr console.log($(this).attr('alt')); }); //Print Your html Code after changing alt attr. $('body').append(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.