Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ternary operator on a element attribute

So I don’t know if this is possible, but I wanted to check for a window.OneTrust object and if it doesn’t exist, to keep the attribute as src, otherwise keep it as data-src and change the type.

Here is what I’m talking about:

If window.OneTrust exists, keep it as:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<script
  type='text/plain'
  id='google-maps-api-script'
  className='optanon-category-C0004'
  data-src="https://maps.googleapis.com/maps/api/js?key=<?php echo get_field('google_maps_api_key', 'option') ?>&v=weekly"
></script>;

Otherwise, have it as:

<script
  type='text/javascript'
  id='google-maps-api-script'
  className='optanon-category-C0004'
  src="https://maps.googleapis.com/maps/api/js?key=<?php echo get_field('google_maps_api_key', 'option') ?>&v=weekly"
></script>;

Is there a way that I can have a ternary operator for type/src instead of doing it like this?

if (!window.OneTrust) {
  <script
    type='text/javascript'
    id='google-maps-api-script'
    className='optanon-category-C0004'
    src="https://maps.googleapis.com/maps/api/js?key=<?php echo get_field('google_maps_api_key', 'option') ?>&v=weekly"
  ></script>;
} else {
  <script
    type='text/plain'
    id='google-maps-api-script'
    className='optanon-category-C0004'
    data-src="https://maps.googleapis.com/maps/api/js?key=<?php echo get_field('google_maps_api_key', 'option') ?>&v=weekly"
  ></script>;
}

>Solution :

You can use document.write in a <script> element.

<script>
if (!window.OneTrust) {
  document.write(`<script
    type='text/javascript'
    id='google-maps-api-script'
    class='optanon-category-C0004'
    src="https://maps.googleapis.com/maps/api/js?key=<?php echo get_field('google_maps_api_key', 'option') ?>&v=weekly"
  ><\/script>`);
} else {
  document.write(`<script
    type='text/plain'
    id='google-maps-api-script'
    class='optanon-category-C0004'
    data-src="https://maps.googleapis.com/maps/api/js?key=<?php echo get_field('google_maps_api_key', 'option') ?>&v=weekly"
  ><\/script>`);
}
</script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading