1

So, the javascript kinda looks like this:

var test = $('#selectelement')
console.log(test)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Now, when running this code, test becomes an array containing the respective element. So if I want to call this select element from the array, I'd have to code

test[0]

Now, this is not much of an issue of course, but I'd like to avoid it since an array is NOT what I need here because only one single element is saved to this variable.

So is there any way to avoid this behavior and instead just have a "normal" variable created (I know JS only knows objects, but at least syntaxwise it should behave like a "normal" variable/primitive value :D)?

2
  • as per your error it seems like you are not including JQuery so please make sure to include it other wise error has occurred like $ is not defined. Commented Nov 13, 2018 at 7:26
  • Do you want to hold it as pure html text? Commented Nov 13, 2018 at 7:31

3 Answers 3

2

it's an array because you return a jquery object :

 document.getElementById('contents'); //returns a HTML DOM Object
 var contents = $('#contents')//array

you can store it in one line

 var contents = $('#contents')[0];  //returns a jQuery Object

JavaScript objects act similar to associative arrays

Sign up to request clarification or add additional context in comments.

1 Comment

woah, thanks, nice to know this ;) Just learned a bit more about the inner workings of native JS and Jquery commands! :D
0

Using the code you had returns the jquery object - what you could do is to get the value of the selected element and use that for the variable. The following code simply updates a variable and consoles it when you change the selected option of the select list.

$('#selectelement').on('change',function(){
  var test = $(this).val();
  console.log(test)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="selectelement">Change me </label>
<select id="selectelement">
  <option selected disabled></option>
  <option>option 1</option>
  <option>option 2</option>
  <option>option 3</option>
  <option>option 4</option>
 </select>

Comments

0

You can always use

var test = ('#selectelement')[0];

or a more JQuery way,

var test = ('#selectelement').get(0);

to get the first element into the variable directly. You can of course also use native functions like this:

var test = document.querySelector("#selectelement");

which will still give you the only element.

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.