skip to Main Content

I am trying to get the text of an option value in a <select> component. I am using the jQuery plugin ‘selectric’.

The following returns an empty string instead of Grid.

const option = $('.selected').text()
console.log(option)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/public/jquery.selectric.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/public/selectric.min.css" rel="stylesheet">

<div class="selectric-scroll">
  <ul>
    <li data-index="0" class="highlighted">List</li>
    <li data-index="1" class="last selected">Grid</li>
  </ul>
</div>

Why does this return an empty string and not Grid? Is there a way to get the text Grid?

I attempted to use text() to obtain text but got empty string.

2

Answers


  1. Chosen as BEST ANSWER

    The reason for the function returning an empty string was that the component hadn't properly loaded in the DOM first before the function was running, so I just added an Add Event Listener:

    window.addEventListener("load", function(event) {
    const option = $('.selected').text()
    console.log(option)
    })
    

  2. If you have your JavaScript code in another external file, then your code would work fine only by adding the defer or async attribute to the script element where you referenced the external script.

    Or you can just place the script at the bottom of the body element.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search