如果子DIV包含特定的CLASS和STYLE属性,则指定DIV ID

Assign a DIV ID if a Child DIV contains a certain CLASS and STYLE attribute

本文关键字:DIV 属性 ID STYLE CLASS 包含特 如果      更新时间:2023-09-26

我有一个使用CMS的网站,我需要保留实际的页面内容并剥离所有标题&页脚代码,但是没有DIV ID标签,我没有访问后端来添加ID。

我的问题是:
如何添加一个DIV ID 'content'到' DIV style="display:inline;float:left;"‘如果其子DIV包含'class="myclass"' AND '样式。width="610px"'使用javascript或jQuery?

谢谢!

这是我今天的代码:

<div>
  <div style="display:inline;float:left;">
    <div class="myclass" style="clear:both;width:610px;display:inline;float:left;">Content A</div>
    <div class="myclass" style="clear:both;width:610px;display:inline;float:left;">Content B</div>
  </div>
</div>

我想把它改成:

<div>
  <div id="content" style="display:inline;float:left;">
    <div class="myclass" style="clear:both;width:610px;display:inline;float:left;">Content A</div>
    <div class="myclass" style="clear:both;width:610px;display:inline;float:left;">Content B</div>
  </div>
</div>

试试这个:

var div$ = $('[style="display:inline;float:left;"]');
var childDiv$ = $('[class="myclass"][style*="width:610px;"]')
if(div$.children(childDiv$).length){
   div$.attr('id','content');
}

如果您确定属性用于样式化,则使用该属性进行搜索。

否则,您需要根据类名进行选择并过滤掉不需要的。请记住,float 'ed元素不能是display: inline;,它总是display: block;

$(function(){
  $(".myclass").each(function() {
    var that = $(this);
    var parent = that.parent();
    if(that.css("width") === "610px" && parent.css("display") == "block" && parent.css("float") == "left") {
        parent.attr("id", "content");
    }
  });  
});