如何使用 jQuery 将属性 rel
替换为 class
,该值也应该更改。所以我只想删除 href
中的所有 rel
并将其替换为 class
属性,但仅限于某个 div
并且仅当它包含图像时?
例如:
<div class="box">
<a href="#" rel="lightbox123">
<img src="#">
</a>
</div>
至
<div class="box">
<a href="#" class="lightbox">
<img src="#">
</a>
</div>
最佳答案
您可以尝试我在评论中提到的内容,在页面中您可以检查元素
并检查是否添加了该类以以红色
显示文本:
<!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>
关于jquery - 使用 jQuery 将属性 rel 替换为 class - 也更改值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45860838/