javascriptgoogle-custom-search

Creating and prepending a div with the Google Custom Search Javascript Callback


I'm using the Javascript callback in Google Custom Search to style the web search results.

https://developers.google.com/custom-search/docs/more_examples

One problem I have is with a simple loop to add a div and text inside each gsc-table-result div.

This mostly works

var SearchResultsRenderedCallback = function() {

let prependdiv = document.getElementsByClassName("gsc-table-result");
    for (let i = 0; i <= 9; i++) {

    let div = document.createElement('div');
    div.className = 'test-div';
    prependdiv[i].prepend('Some text', div);
        }

};

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

But. The text "Some text" is outside of the test-div, like this:

enter image description here

Why doesn't prependdiv[i].prepend('Some text', div); put the text inside the div?


Solution

  • prepend('Some text', div) adds the text and div as separate children. To put the text inside the div, set div.textContent first:

    var SearchResultsRenderedCallback = function() {
        let prependdiv = document.getElementsByClassName("gsc-table-result");
        for (let i = 0; i < prependdiv.length && i < 10; i++) {
            let div = document.createElement('div');
            div.className = 'test-div';
            div.textContent = 'Some text';
            prependdiv[i].prepend(div);
        }
    };
    window.__gcse = window.__gcse || {};
    window.__gcse.searchCallbacks = { web: { rendered: SearchResultsRenderedCallback } };