I'm working with html and in this job I would like get one help from you
Look the following question
I have this div
<div >
<h1 >Test 1</h1>
</div>
<div >
<h1 >Test 2</h1>
</div>
<div >
<h1 >Test 3</h1>
</div>
<div >
<h1 >Test 4</h1>
</div>
I would to do one loop to get the text from h1 to hide if text is Test 1
I'm trying like this:
var htmlCollection = document.getElementsByClassName('my-class')
console.log(htmlCollection);
Array.prototype.slice.call(htmlCollection).forEach(element => {
console.log(element);
});
or
Like this:
var htmlCollection = document.getElementsByClassName('bs-media-item-card-array-1')
var BoxArray = Array.from(htmlCollection);
console.log(BoxArray);
Or
var htmlCollection = document.getElementsByClassName('bs-media-item-card-array-1')
for(index of htmlCollection){
console.log(index);
}
Or
for(index in htmlCollection){
if(index <= htmlCollection.length) {
console.log(htmlCollection[index]);
}
}
The return from
var htmlCollection = document.getElementsByClassName('my-class')
Is this
HTMLCollection []
0: div.my-class
1: div.my-class
2: div.my-class
3: div.my-class
length: 4
[[Prototype]]: HTMLCollection
UPDATE
Sometimes I tried to use like this, too
<div >
<a >
<h1 >Test 2</h1>
</a>
</div>
<div >
<a >
<h1 >Test 3</h1>
</a>
</div>
Thanks for help me
CodePudding user response:
Use querySelector()
to find the element in the div and test its text.
var divs = document.querySelectorAll('.my-class')
divs.forEach(div => {
if (div.querySelector(".title").innerText == 'Test 1') {
div.classList.add('hidden');
}
})
.hidden {
display: none;
}
<div >
<h1 >Test 1</h1>
</div>
<div >
<a >
<h1 >Test 2</h1>
</a>
</div>
<div >
<a >
<h1 >Test 3</h1>
</a>
</div>
<div >
<h1 >Test 4</h1>
</div>
CodePudding user response:
You can combine everything in querySelectorAll()
,
then use element.closest()
document
.querySelectorAll('div.my-class > h1.title')
.forEach( elm =>
{
if (elm.textContent.includes('Test 1'))
elm.closest('div.my-class').classList.add('noDisplay')
})
.noDisplay {
display: none;
}
<div >
<h1 >Test 1</h1>
</div>
<div >
<h1 >Test 2</h1>
</div>
<div >
<h1 >Test 3</h1>
</div>
<div >
<h1 >Test 4</h1>
</div>
CodePudding user response:
// Get all the h1 elements with a class of title inside elements with a class of my-class and filter the ones where the text is Test 1
const elementsToHide =
[...document.querySelectorAll('div.my-class > h1.title')]
.filter(node => node.innerText === 'Test 1');
//Hide them
elementsToHide.forEach(h1 => h1.classList.add('hide'));
.hide {
display: none;
}
<div >
<h1 >Test 1</h1>
</div>
<div >
<h1 >Test 2</h1>
</div>
<div >
<h1 >Test 3</h1>
</div>
<div >
<h1 >Test 4</h1>
</div>