Javascript - Get Every Div That Doesn't Contain A Child Specific Element
I have a div group inside some that I want to have a class for every div that doesn't have a specific element like h1 For Example :
Solution 1:
Step 1: Get all div elements.
Step 2: Filter the collection, keeping those that do not have an h1 descendant.
Step 3: For each matching element, map the element to its className property.
Step 4: There is no step 4.
[...document.querySelectorAll('div')].filter(d => !d.querySelector('h1')).map(d => d.className)
constMy_HTML = `
<div class="container">
<div class="parents">
<h1>AAAA</h1>
<div class="content">
<p>Hello</p>
</div>
</div>
</div>
`;
const parser = newDOMParser();
const doc = parser.parseFromString(My_HTML, "text/html");
const everyDiv= [...doc.querySelectorAll('div')].filter(d => !d.querySelector('h1')).map(d => d.className);
console.log(everyDiv)Solution 2:
Consider the following.
$(function() {
$(".container *").each(function(i, el) {
console.log("Check Elements", $(el).prop("nodeName"), $(el).attr("class"));
if (!$(el).is("h1")) {
console.log("Class: " + $(el).attr("class"));
}
});
});<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><divclass="container"><divclass="parents"><h1>AAAA</h1><divclass="content"><p>Hello</p></div></div></div>This itereates each of the elements within .container; only looking for a Class if it is not an <h1> element.
You could also use the :not() selector.
$(function() {
$(".container *:not(h1)").each(function(i, el) {
console.log("Check Elements", $(el).prop("nodeName"), $(el).attr("class"));
});
});
This will select the child elements that are not H1.
Post a Comment for "Javascript - Get Every Div That Doesn't Contain A Child Specific Element"