简体   繁体   中英

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:

<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> .

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. 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 . If the selector selects at lease one element then the div.class has children as you expect.

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.

With jQuery, you can use .has() to narrow your selection and even chain other methods, as in:

$(".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.

Documentation on jQuery's .has() -- https://api.jquery.com/has/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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