简体   繁体   中英

jQuery: get the normal JS format of a html element

I am using jQuery and everything works fine except a few stuff. There are a few things you cannot do with the jQuery format of an element but only with the simple JS format. Especially, when using the hasAttributes() in simple JS.

This works:

 let fooDiv = document.getElementsByTagName("div")[0]; console.log(fooDiv.hasAttributes()); //returns false as expected let barDiv = document.getElementsByTagName("div")[1]; console.log(barDiv.hasAttributes()); //returns true as expected
 <div>foo</div> <div id="id">bar</div>

This doesn't:

 let fooDiv = $(document.getElementsByTagName("div")[0]) //creates a jQ object console.log(fooDiv.hasAttributes()); //error let barDiv = $(document.getElementsByTagName("div")[1]) //creates a jQ object console.log(barDiv.hasAttributes()); //error
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div>foo</div> <div id="id">bar</div>

I am aware that the jQuery hasAttr() exists but I want to get the JS format of a jQuery object. There are a lot of differences, for example the jQuery creates an object but otherwise it is a html node list.

Initially, my question is:

How do I get the html node list or html element or the simple JS format of a html element(s) from jQuery?

To expand on what blex said in the comments ... when jQuery is used to select an HTML element, the raw HTML is always collected in an array as part of the variable you assign it to. For example, using your code:

// grab the element or elements
let fooDiv = $(document.getElementsByTagName("div")[0]);

// lets see the HTML!
consoe.log( fooDiv[0] ); 

The HTML itself will be exposed in that array, allowing direct access to the HTML and its properties... for example:

console.log( fooDiv[0].innerHTML );

or

console.log( fooDiv[0].tagName );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM