如何使用jQuery将属性rel
替换为class
,还应更改该值。所以我只想删除rel
中的所有href
并将其替换为class
属性,但只能在某个div
内,并且仅在包含图片的情况下?< / p>
例如:
<div class="box">
<a href="#" rel="lightbox123">
<img src="#">
</a>
</div>
到
<div class="box">
<a href="#" class="lightbox">
<img src="#">
</a>
</div>
答案 0 :(得分:0)
这应该
$(".box a:has(img)").attr("class", function(){
var val = $(this).attr("rel");
$(this).removeAttr("rel");
return val;
});
console.log($(".box")[0].outerHTML)
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
<a href="#" rel="lightbox123">
<img src="#">
</a>
</div>
&#13;
答案 1 :(得分:0)
您可以尝试我在评论中提到的内容,在您可以inspect element
的页面中检查是否已添加该课程以red
颜色显示文字:
<!DOCTYPE html>
<html>
<head>
<style>
.lightbox{color: red;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var getTagName = $(".box a:has(img)").parent(); //returns DIV, as $(".box a:has(img)") returns ANCHOR tag
//$(".box a:first-child").removeAttr("rel"); //this will remove rel attribute from first child of box class without checking if anchor tag has child as img, hence not good.
//$(".box a:first-child").addClass("lightbox"); // this will add class to the first child without checking img tag, hence not recommendable
if(getTagName.prop("tagName")=="DIV") //Note that tagName returned in CAPS
{
$(".box a:has(img)").removeAttr("rel").addClass("lightbox");// This removes rel attribute
}
});
</script>
</head>
<body>
<div class="box">
<a href="#" rel="lightbox123">
<img src="#" alt="alternate text">
</a>
</div>
</body>
</html>
&#13;