[英]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.