Getting html DOM element from JQuery element - javascript

Below code gives me JQuery object, which includes JQuery functions associated with.
var element = $("#element");
But how can I get the HTML DOM element from the above JQuery object ?

Fetch first item from jQuery object
var element = $("#element")[0];

You can use get (link to API).
element.get()
It will return an array.

Related

Jquery custom attribute access

there is a div present in my js file
<div id="myid" data="mydata"></div>
when i try to access custom attribute data with pure javascript
var data = document.getElementById('myid').getAttribute('data');
jquery alone
var data = $("#"+myid).attr('data');
above both mwthods are working properly but when i try to used the both jquery and javascript
var data = $("#"+myid).getAtrribute("data");
then is is giving error? but didn't able to get the reason ? can anyone explain please?
You are applying a dom method to a jquery object which causes error instead jquery has a method to convert the selector to the dom element .get():
$("#"+myid).get(0).getAtrribute("data");
alert($('#myid').get(0).getAttribute('data'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myid" data="mydata"></div>
As you are using a data attribute then better to use data-* attribute and jQuery has a method to get it with .data() method:
<div id="myid" data-mydata="CustomisedData"></div>
then in the jQuery:
$('#myid').data('mydata'); // will give you "CustomisedData"
Because $("#"+myid) is a jQuery instance, not HTML Element object. So you can't use DOM methods on some arbitrary object.
jQuery instance object is an array-like collection of DOM elements. It means that you can extract individual DOM element from it by index if you really need. So in your case you could do this:
$("#" + myid)[0].getAtrribute("data");
jQuery also offers dedicated method for it $.fn.get:
$("#" + myid).get(0).getAtrribute("data");
This should work:
var data = $("#"+myid)[0].getAtrribute("data");
Because to use javascript code, you need to use DOM object but jQuery uses array-like collection object.

Edit results of outerHTML with jQuery

I'm trying to read in the entire page's HTML (including the doctype) then remove a few parts of the page in order to pass it as a string via AJAX.
What I have so far is:
var page = doctype + document.documentElement.outerHTML;
This gives me the content that I want, but when I try to use jQuery's .remove() function, I'm getting undefined is not a function.
page.remove(".my-class");
I assume I'm doing something with the variable type wrong? How can I grab the full page source such that I can still manipulate it with jQuery?
You need to put the html into a jQuery object in order to manipulate it. After you do that you can use the jQuery's find method then remove method to remove elements that match .my-class:
var $page = $(doctype + document.documentElement.outerHTML);
$page.find(".my-class").remove();
After that you can get the resulting html by doing:
var htmlToSendViaAjax = $page[0].outerHTML;
If you want to manipulate HTML with jQuery, you have to call the jQuery constructor:
var page = $(doctype + document.documentElement.outerHTML);
page.remove(".my-class");
Your problem is that page is not a jQuery object and as such doesn't have methods like .remove().
If you want the outerHTML with jQuery, you need to make a jQuery selection:
$("#selector");
$(document); // for the entire document
Then you can use a solution found here to get the outerHTML of the first element in the selection (you can use a for or each loop if you do it for lots of elements:
var $selection = $("#selector")
$selection[0].outerHTML;

Why would jQuery return undefined for the css function of an element?

jQuery 1.11.1, on Mac OS X Mavericks, latest version of Safari.
I'm trying to set CSS properties with the css function. css() is missing from elements.
First, I validated that the element is selected correctly:
// There is only one element that has id="container"
var $container = $('#container');
// Selector returns a collection. I have to access first element:
console.log($container[0]); // prints HTMLDivElement
// css function is undefined
console.log($container[0].css); // prints undefined
// Also can't set any css value. Gives undefined error.
$container[0].css({backgroundColor:'blue'});
The error is:
TypeError: 'undefined' is not a function (evaluating
'$container[0].css({backgroundColor:'blue'})')
I removed everything from the test page. It includes jQuery, and within the body it has the div with the ID. Very simple. Beneath that, there is the JavaScript code shown above.
Any idea why the div would be lacking the css function?
It is because you are dropping out of the jQuery object and are using the DOM element...
$container[0].css({backgroundColor:'blue'});
The [0] here gets you the DOM object from the jQuery object.
Use jQuery if you want to access the jQuery method...
$container.css({backgroundColor:'blue'});
You're using jQuery incorrectly. When you say $container[0] you are getting the first javascript DOM element of the jQuery object (which doesn't have any jquery functions attached to it). If you want to get the css background color of the element using jQuery you need to do $container.css("background-color"), and to set it $container.css("background-color", "blue"); or $container.css({ "background-color": "blue" });
Because the css function is a method of a jquery object. When you do $container[0] you get the first DOM node that matched the selector, which is not a jquery object.
Try $container.css(...).
When you access the collection items, no longer has the jQuery methods, only the DOM elements.
You could replace:
$container[0].css({backgroundColor:'blue'});
by
$container.css({backgroundColor:'blue'});
If you have one more div element with the same css attribute,
for instance lets say below statement returns more than one result:
var $container = $('.container'); // Has 3 results
And you want to reach specific elements css attribute then you can revert the dom element into jquery element and do what you want as below:
$($('.container').get(2)).css({ "background-color": "blue" });
http://jsfiddle.net/JNR63/
check this example
alert($container.css("width"));

jQuery using .toggle() to toggle a single element

So I want to toggle a single element in an array of elements how can I do this?
What I have tried
$(".classname")[1].toggle()
The problem with that is that you are getting the element rather than a jquery object. Try this:
$(".classname").eq(1).toggle()
Also, I assume you are looking for the 2nd element using index 1
Try this :
$('.classname').eq(0).toggle()
When using [], you are losing jquery reference and the object become a dom element. DOM element are used with Javascript. Example :
$('.classname')[0].id //will work since .id is a DOM attribute
$('.classname').eq(0).id //will not work since it's a jQuery object
Here the jQuery .eq() information page.
Elements are based on a 0 index, wich mean 0 = first element, 1 = second element and go on

What's the opposite of jQuery `.get()`?

.get() converts a jQuery object to a DOM element that Javascript can use without jQuery.
If I have a DOM element, how can I convert it to a jQuery object?
jQuery core syntax accepts DOM elements: $(theDomElement).
jQuery( element )
element A DOM element to wrap in a jQuery object.
Recall that you're doing this every time you write $(this).
var myDOMElement = document.getElementById("myDomId");
var myDOMElementConvertedTojQueryObject = $(myDOMElement);

Categories