Date: 2023oct17
Language: javaScript
Q. jQuery: how to get anything from an HTML element
A. Assuming we have this
const mytag = $('#mytag');
Content
const contents = mytag.contents();
const innerHtml = mytag.html();
const outerHtml = mytag.prop('outerHTML');
const parent = mytag.parent();
const children = mytag.children();
const anything = mytag.find('your query goes here');
Use prop() for properties
(Since jQuery 1.6 - long ago)
const tagName = mytag.prop('tagName').toLowerCase();
https://developer.mozilla.org/en-US/docs/Web/API/Element/tagName
const nodeName = mytag.prop('nodeName').toLowerCase();
https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeName
// for <input>
const isDisabled = mytag.prop('disabled');
// for <input>
const isReadOnly = mytag.prop('readonly');
// for <input type=checkbox>
const isChecked = mytag.prop('checked');
The jQuery docs say to use prop() for "selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected". Its odd they don't
mention disabled, readonly and checked which I use a lot more.
https://api.jquery.com/prop
Use attr() for attributes
const id = mytag.attr('id');
const name = mytag.attr('name');
const type = mytag.attr('type'); // in <input>
const cls = mytag.attr('class');
const style = mytag.attr('style');
const title = mytag.attr('title');
const alt = mytag.attr('alt'); // in <img>
const placeholder = mytag.attr('placeholder');
const src = mytag.attr('src'); // in <img>
const href = mytag.attr('href'); // in <a>
const labeledBy = mytag.attr('aria-labelledby'); // accessibility
const controls = mytag.attr('controls'); // media
const preload = mytag.attr('preload'); // media
const source = mytag.attr('source'); // media
// ... many more
// Older
const width = mytag.attr('width'); // Use css
const height = mytag.attr('height'); // Use css
// For your custom attributes
// In theory they're supposed to prefixed by 'data-';
const helloWorld = mytag.attr('data-hello-world');
// But you can get away with nearly anything
const helloWorld = mytag.attr('hello-world');
Value is dynamic so use
const value = mytag.prop('value'); // WRONG
const value = mytag.val(); // for <input type=text> not type=checkbox
To get computed CSS/style
const backgroundColor = mytag.css('background-color');
const width = mytag.css('width'); // only works after loaded
const height = mytag.css('height'); // only works after loaded
const maxWidth = mytag.css('max-width');
const maxHeight = mytag.css('max-height');
const myCssVar = mytag.css('--my-css-variable'); // custom prop
// .. many more
Misc
const first = mytag.first();
const firstChild = mytag.children().first();
const last = mytag.last();
const clone = mytag.clone();
Please let us know of any mistakes here.