jquery - 使用 jQuery 将属性 rel 替换为 class - 也更改值

标签 jquery

如何使用 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/

相关文章:

javascript - 通过js键码允许带有数值的点/句号

jquery - 如何检查用户是否在iPhone设置中限制了相机

javascript - jQuery .load()/.ajax() 在附加后不在返回的 HTML 中执行 javascript

javascript - 刷新页面不刷新滚动条javascript

jQuery - 获取 parent 孙子的 value()

javascript - 如何让IE的Javascript实现 'this'关键字功能?

JQuery UI 菜单项阻止默认链接行为

c# - 右键单击时如何关闭/删除菜单项或选项卡?

jquery - 获取接下来的 6 个结果

jQuery click() 事件包罗万象?