Search code examples
javascriptgoogle-searchgoogle-custom-searchgetelementsbyclassnamegoogle-search-api

Changing nested markup with getElementsByClassName


I'm working with the API of Google's Programmable Search Engine and using a callback to chnage the stying of output, specificaly the font size of the title of each search result snippet.

What I have below works and changes the gs-title font size to 24px. But the problem is that some gs-title divs have the search term inside <b> and </b> tags, and so that the title is rendered at 24px, but inside the bold tags, the font is the original size. See the image below with the search term "test".

Area culinary students <b>test</b> their kitchen skills in 'Chopped' cooking ...

image showing title rendered

How can I also apply fontSize to text inside the bold tags?

Fiddle: https://jsfiddle.net/jqh4ntdv/

SearchResultsRenderedCallback = function(){

var elements = document.getElementsByClassName('gs-title');
for (var i = 0; i < elements.length; i++) {
  var element = elements[i];
  element.style.fontSize = "24px";
}

};

window.__gcse || (window.__gcse = {});
window.__gcse.searchCallbacks = {
  web: {
      rendered: SearchResultsRenderedCallback,
  },
};

Solution

  • You can apply the same styling to the children of an HTML element by using the children property:

    let elements = document.getElementsByClassName('gs-title');
      for (const element of elements) {
        element.style.fontSize = "24px";
          for (const child of element.children) {
            child.style.fontSize = "24px";
          }
      }