javascript管理DOM:获取、设置、删除

93 阅读1分钟

当dom加载完成,执行代码

const ready = function (cb) {
  // Check if the `document` is loaded completely
  document.readyState === "loading"
    ? document.addEventListener("DOMContentLoaded", function (e) {
        cb();
      })
    : cb();
};
ready(function() {
    // 当dom加载完成
    ...
});

从元素上获取css styles

我们可以通过 getComputedStyle 方法获取所有 CSS 样式

const styles = window.getComputedStyle(el, null);

可以通过以下方式获取特定值

const bgColor = styles.backgroundColor;
const textSizeAdjust = styles['-webkit-text-size-adjust'];
const bgColor = styles.getPropertyValue('background-color');
const bgColor = styles.getPropertyValue('backgroundColor');

获取设置title

const title = document.title;
document.title = 'Hello World';

获取设置HTML

const html = el.innerHTML;
el.innerHTML = '<h1>Hello World!</h1>';

获取、设置、删除attributes

const title = link.getAttribute('title');

image.setAttribute('width', '100px');
image.setAttribute('height', '120px');

el.removeAttribute('title');

获取、设置、删除data attributes

const message = el.getAttribute('data-message');
// 或者
const message = el.dataset.message;

ele.setAttribute('data-message', 'Hello World');
// 或者
el.dataset.message = 'Hello World';

el.removeAttribute('data-message');
// 或者
delete ele.dataset.message;

获取元素的兄弟姐妹

//获取上一个兄弟
const prev = el.previousSibling;

//获取下一个姐妹
const next = el.nextSibling;

//获取所有兄妹
const parent = el.parentNode;
const siblings = [].slice.call(parent.children).filter(function (child) {
    return child !== el;
});

匹配特定选择器且离当前元素最近的祖先元素

const result = el.closest(selector);

获取文档的高度和宽度

//包括滚动条部分
const fullHeight = Math.max(
    document.body.scrollHeight,
    document.documentElement.scrollHeight,
    document.body.offsetHeight,
    document.documentElement.offsetHeight,
    document.body.clientHeight,
    document.documentElement.clientHeight
);

const fullWidth = Math.max(
    document.body.scrollWidth,
    document.documentElement.scrollWidth,
    document.body.offsetWidth,
    document.documentElement.offsetWidth,
    document.body.clientWidth,
    document.documentElement.clientWidth
);

获取元素的父节点

const parent = el.parentNode;

获取一个元素相对于另一个元素的位置

const elRect = el.getBoundingClientRect();
const targetRect = el.getBoundingClientRect();

const top = elRect.top - targetRect.top;
const left = elRect.left - targetRect.left;

获取元素相对于文档的位置

const rect = el.getBoundingClientRect();
const top = rect.top + document.body.scrollTop;
const left = rect.left + document.body.scrollLeft;

获取选定的文本

const selectedText = window.getSelection().toString();

获取元素的文本内容

const text = el.textContent;

每天一个javascript操作dom方法,学到了,点个赞吧