2

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?

1 Answer 1

3

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 } };
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.