I have tried for several hours to get this to work without any success. I have a site that lists recent posts. I need to insert text into any blank divs within that site. below is the html
<div class="pt-cv-taxoterm below_title"></div>
I haven’t used javascript in many years and so I’m really rusty. I’ve searched on here and found several solutions but none of them work for me for some reason.
Here’s a few that i’ve tried:
if (document.getElementsByClassName('div.pt-cv-taxoterm.below_title').is(':empty')) {
document.getElementsByClassName('div.pt-cv-taxoterm.below_title').innerHTML = '<a href="https://revtommy.com/sermons/" title="Sermons" class="pt-cv-tax-blog">Sermons</a>';
}
if ($('.pt-cv-taxoterm below_title').is(':empty')){
document.getElementsByClassName('pt-cv-taxoterm below_title').innerHTML = '<a href="https://revtommy.com/sermons/" title="Sermons" class="pt-cv-tax-blog">Sermons</a>';
}
This is a WordPress site and I’m using a plugin to generate this particular block. It has a spot to add either custom CSS or Javascript for that plugin. Any help would be appreciated.
I tried multiple things that I found on this site.
4
Answers
You can update your jquery selector as
$('.pt-cv-taxoterm.below_title:empty')
, please note there is no space between both classes mentioned in selector and append:empty
so that it will only return empty div.Since this selector will return an array, you need to use
each
function to loop over the array. Inside the function you can use$(element).html()
function to update thehtml
content inside given div.Try like below.
References
Alternatively if you wish to with plain
javascript
and not usingjquery
then try like below.Use
let elements = document.getElementsByClassName('pt-cv-taxoterm below_title');
to get element list with given classes. Note thatselector
does not havediv
inside it. Alsoclass
names will have space between them and there it won’t be appended by.
.We need to convert
elements
into array withArray.from(elements)
and loop over it usingforEach
. Inside it we need to check if it is empty or not usinghasChildNodes()
and updateinnerHTML
if it is empty.References
This code listens for the DOMContentLoaded event, which ensures that the DOM is fully loaded before executing the JavaScript code. It then selects all elements with the specified classes, checks if they are empty, and if so, inserts the desired HTML content into them.
Here’s a simple example of how to insert text into an empty using JavaScript:
You can get all DIVS with a specified class or ID using
querySelectorAll
then one can pass
.innerHTMl
to insert desired content. I would recommend for larger loops or content applications use a libary like react or built-in functions like.createElement
andappend
.Also in this scenario using
.is(':empty')
is not really a good solution as we can just useequals false
, or the.trim()
solution wich works.