-1

I'm having a little problem with task for my new company. I need to write a script that basicly creates a html text and puts it on site using class selector (after a div to be sepcific). The problem is that we're using a custom CMS without any JS library so it has to be plain and the other obstacle I need to run only when element is loaded on page already (some kind of WaitForElement function is needed). JS noob here - can someone suggest a solution? Thank you in advance

I've tried a simple solution:

node = document.getElementsByClassName('class1 class2');
node.insertAdjacentHTML('afterend', '<p>text</p>');

And I've put something like this:

function waitForElement(elementId, callBack) { window.setTimeout(function() { var element = document.querySelectorAll(elementId); if (element.length) { callBack(elementId, element);} else { waitForElement(elementId, callBack); }}}

However I'm struggling to merge those two and running them on site.

Qhr
  • 33
  • 3
  • 1
    This is not a we code it for you site. What have you tried, what didn't work? If you have 0 clue ask your company to hire someone who know this kind of stuff. – cloned Aug 16 '22 at 06:31
  • I have tried a pretty simple and easy solution: 'node = document.getElementsByClassName('.class1.class2'); node.insertAdjacentHTML('afterend', '

    text

    ');' However the problem is that I don't know how to make it run only after the element on page is loaded.
    – Qhr Aug 16 '22 at 06:38
  • Add all this code you tried to the question itself, not to the comments. – cloned Aug 16 '22 at 07:18
  • There's not enough information to answer this question. Perhaps it's better to ask the CMS producer. – KooiInc Aug 16 '22 at 07:41
  • `document.getElementsByClassName('.class1.class2')` - that's not how `getElementsByClassName` works. Read: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName – CBroe Aug 16 '22 at 08:16
  • Ahh I see, mismatched it with querySelector. Thx – Qhr Aug 16 '22 at 08:33

1 Answers1

-1

what CMS are you using? Could you control the element?

I think you can use the MutationObserver API like this. or call the function after the element loaded

sayandcode
  • 1,775
  • 1
  • 11
  • 24
X-Ray
  • 59
  • 6
  • Unfortunetly it's a custom CMS made only for my company. Basicly I don't need to control the element. It's supposed to be small text added to a place on a site - it has to be in JS cuz that specific place is inaccessible otherwise. So I only have to write it in script – Qhr Aug 16 '22 at 06:48
  • @Qhr Perhaps you should give your starting point code, so that we can help you better – sayandcode Aug 16 '22 at 07:38
  • Done, I've put it in my initial question. Sorry – Qhr Aug 16 '22 at 07:39