admin管理员组文章数量:1400599
if iam getting value of x and y by document method than its ok but if i get value of x and y by directly as below which is mented out by me than i get error why this is so?
<!DOCTYPE html>
<html>
<head>
<script src=".11.1/jquery.min.js"></script>
</head>
<body>
Select a fruit and click the button:
<select id="mySelect">
<option value="11">Apple</option>
<option value="12">Orange</option>
<option value="13">Pineapple</option>
<option value="14">Banana</option>
</select>
<button type="button" onclick="myFunction()">Display index</button>
<script>
function myFunction() {
var x = document.getElementById("mySelect").selectedIndex;
var y = document.getElementById("mySelect").options;
//var x = $("#mySelect").selectedIndex;
//var y = $("#mySelect").options;
alert("Index: " + y[x].index + " text is " + y[x].text + " and value is " + y[x].value);
}
</script>
</body>
</html>
if iam getting value of x and y by document method than its ok but if i get value of x and y by directly as below which is mented out by me than i get error why this is so?
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
Select a fruit and click the button:
<select id="mySelect">
<option value="11">Apple</option>
<option value="12">Orange</option>
<option value="13">Pineapple</option>
<option value="14">Banana</option>
</select>
<button type="button" onclick="myFunction()">Display index</button>
<script>
function myFunction() {
var x = document.getElementById("mySelect").selectedIndex;
var y = document.getElementById("mySelect").options;
//var x = $("#mySelect").selectedIndex;
//var y = $("#mySelect").options;
alert("Index: " + y[x].index + " text is " + y[x].text + " and value is " + y[x].value);
}
</script>
</body>
</html>
Share
Improve this question
edited Nov 10, 2014 at 13:07
sampathsris
22.3k12 gold badges72 silver badges101 bronze badges
asked Nov 10, 2014 at 12:13
kki3908050kki3908050
1652 silver badges9 bronze badges
4
-
do you really have added
jQuery
outside the<html>
? – Mohammad Faisal Commented Nov 10, 2014 at 12:17 - yes i was just testing please see link below jsfiddle/3908050/wbo2nhsq/2 – kki3908050 Commented Nov 10, 2014 at 12:20
-
you should place that
<script>
in<head>
also the fiddle is not giving any alert message – Mohammad Faisal Commented Nov 10, 2014 at 12:21 - now script inside head ,and why it say in fiddle that myfunction is not defined – kki3908050 Commented Nov 10, 2014 at 12:26
6 Answers
Reset to default 3i get error why this is so
Because the object returned by the jQuery constructor doesn't have selectedIndex
or options
properties.
$('selector')
creates a jQuery collection out of matches in the DOM whereas document.getElementId('selector')
is a reference to a specific DOM element.
$('selector')
contains a reference to the DOM element, but doesn't have DOM element properties/methods, instead it has jQuery methods.
To use DOM element properties/methods, you can 'get' the DOM element from the jQuery collection using square bracket notation, since our jQuery collection is an array-like object:
var x = $("#mySelect")[0].selectedIndex;
var y = $("#mySelect")[0].options;
Or, using .get()
:
var x = $("#mySelect").get(0).selectedIndex;
var y = $("#mySelect").get(0).options;
Or, return a property value using .prop()
:
var x = $("#mySelect").prop('selectedIndex');
var y = $("#mySelect").prop('options');
- For document.getElementById(“id”) vs $(“#id”) see this question
var x = $("#mySelect").selectedIndex; var y = $("#mySelect").options;
selectedIndex
and options
are undefined
. You should use .text()
and .val()
- Solution for your snippet
$('#btn').on('click', function() { // var x = document.getElementById("mySelect").selectedIndex; // var y = document.getElementById("mySelect").options; var x = $("#mySelect").val(); var y = $("#mySelect option:selected").text(); alert(x + " :: " + y); //alert("Index: " + y[x].index + " text is " + y[x].text + " and value is " + y[x].value); });
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script> Select a fruit and click the button: <select id="mySelect"> <option value="11">Apple</option> <option value="12">Orange</option> <option value="13">Pineapple</option> <option value="14">Banana</option> </select> <button type="button" id="btn">Display index</button>
the fiddle
Those methods dont live on the jQuery object, you can console.log the object and see what they inherit through their prototype chain.
From MDN:
Summary Returns a reference to the element by its ID.
Syntax element = document.getElementById(id); where
element is a reference to an Element object, or null if an element with the specified ID is not in the document.
The important part to take away is the reference to the Element object.
Here you can see the methods that are available from this object.
$() is a jQuery Object Constructor, it will make a jQuery object and wrap the selected elements inside this object (all DOM properties can still be accesed but not directly).
getElementById() is a native javascript function that retrieves the DOM element which has its normal properties.
You usually don't need to access the DOM element within the jQuery Object as you can use the jQuery methods living inside the Object that will manipulate the selected elements. It's a little bit tricky with selects as I don't see any methods just to retrieve the options list however:
$('#select option'); //Selects all the options of the select
$('#select option').each(function(){
//iterate all options of the select.
});
$('#select option:selected'); //Get the selected option.
Would be fair equivalent. From then on you can use jQuery methods to manipulate the options, for example:
$('#select option:selected').text(); //Option text
$('#select option:selected').val(); //Value of option
$("...")
returns a jQuery collection that contains the matched elements. You cannot access the elements and their properties directly, instead:
Use the jQuery.get
accessor method:
var x = $("#mySelect").get(0).selectedIndex;
var y = $("#mySelect").get(0).options;
Dereference the element:
var x = $("#mySelect")[0].selectedIndex;
var y = $("#mySelect")[0].options;
Use jQuery.prop
:
var x = $("#mySelect").prop("selectedIndex");
var y = $("#mySelect").prop("options");
Having said all that, you can change your code to this:
var $selectedOption = $("#mySelect option:selected");
console.log(
$selectedOption.index(),
$selectedOption.text(),
$selectedOption.val()
);
$("#element"); is a jquery css-syntax-like DOM selector gathering all matching results in an array of jQuery objects which can access the full scale of jQuery functions which are very handy and easy to use out of the box.
while "doucment.getElementById("element);" is a native JavaScript function.
JQuery is an abstraction layer for JavaScript with an easier syntax, powerful tools/functions out of the box and is also fixing browser patiblity issues for you.
Short to say it executes JavaScript for you in the background you do not have to bother with.
You should try to get used to code jQuery whenever possible as it makes your life easier and you dont have to bother with plex and tons of lins of code with only small effect such as for example: writing a AJAX request natively in JavaScript is like 15 more lins of code pared to jQuery with the total same effect.
Some examples that do exactly the same thing:
Access element
JavaScript:
alert(document.getElementById("element").name);
JQuery:
alert($("#element").attr("name"));
Loop elements
JavaScript:
var elements = document.getElementsByClassName("class");
for(var i = 0; i < elements.length; i++) {
alert(var element = elements[i].name);
}
JQuery:
$(".class").each(function() {
alert($(this).attr("name")); //This accesses the current element of each function as a full useable and handy object
});
This are only two examples and you can see that it is indeed very powerful. Small code doing exactly the same as big code in plain JavaSCript. When you are including jQUery you should always try to use its full potential.
--
Your code in JQuery style:
<button id="btn_display_index" type="button">Display index</button>
<script type="text/javascript">
//Will be executed any time the button with id "btn_display_index" is clicked!
$("#btn_display_index").on("click", function() {
var currentOption = $("#mySelect option:selected");
alert("Index: " + currentOption.attr("value") + " - Value: " + currentOption.html());
});
</script>
本文标签: javascriptdocumentgetElementById(quotidquot) vs (quotidquot)Stack Overflow
版权声明:本文标题:javascript - document.getElementById("id") vs $("#id") - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744182649a2594139.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论