简体   繁体   English

根据条件替换未知命名元素的inner.html

[英]Replacing the inner.html of an unknown named element based on condition

I run into this problem frequently and never know the best approach. 我经常遇到这个问题,却从来不知道最好的方法。 Imagine I have a structure that includes several instances of the following html: 想象一下,我有一个结构,其中包含以下html的多个实例:

<div class="known">
    <div class="another unknown">
        <div class="unknown">
            <h4>Something a something</H4>
        </div>
    </div>
</div>

For each div of class known, I want to change the inner html of that div only if it contains a div inside it with some particular tag, in this case <h4> . 对于已知的每个div类,我只想更改该div的内部html,前提是该div的内部html中包含带有特定标记的div,在这种情况下为<h4>

What is the best way to achieve that. 实现此目标的最佳方法是什么。 I know that I could do it by taking the inner html of class known and doing a regex match. 我知道我可以通过采用已知类的内部html并进行正则表达式匹配来做到这一点。 But is there a more robust way based on tags? 但是,是否有基于标签的更可靠的方法?

Simple, just use a selector that spans over the div.known and restrict it's context to div h4 . 很简单,只需使用跨越div.known的选择器并将其上下文限制为div h4 If the selector selects at lease one element then the div.class has children as you expect. 如果选择器至少选择一个元素,则div.class具有您期望的子级。

if( $('.known div h4').length > 0 ){
    $('.known').html('Some html');
}

Yes! 是! You can do this. 你可以这样做。

var head = Array.prototype.slice.call(document.querySelectorAll("h4 #known"));
for(var i = 0; i < head.length; i++)
{
    while(head[i].className !== "known")
        head[i] = head[i].parent();
}

Now head will be an array of all the DOM elements have the tag known and have h4 's in them. 现在head将是所有DOM元素的数组,这些元素具有known的标签,并在其中包含h4

With jQuery, you can use .has() to narrow your selection and even chain other methods, as in: 使用jQuery,您可以使用.has()来缩小选择范围,甚至链接其他方法,如下所示:

$(".known").has("h4").css("background","red");

Check out this fiddle for example. 例如查看这个小提琴 Notice that clicking the button will change the color of any div.known only if that element contains an h4 tag as a descendant. 请注意,仅当该元素包含作为后代的h4标记时,单击按钮才会更改任何已知的div。的颜色。

Documentation on jQuery's .has() -- https://api.jquery.com/has/ 在jQuery的。先后()文档- https://api.jquery.com/has/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM