標籤:
總結與複習原生與jquery的DOM操作。
擷取元素節點:
$(".class")$("#id")$(".class div")$(".class div:first")document.querySelector(‘.class‘);document.querySelector(‘#id‘);document.querySelector(‘.xxx div‘);document.querySelector(‘.class div:first-child‘);document.querySelectorAll(‘li‘)
插入HTML:
$(selector).before(content)$(selector).after(content)$(parent).append(content)parent.appendChild(content)ele.insertBefore(node,ele.childNodes[0]);
擷取子節點:
$(".class").childern();ele.childNodes;
擷取父節點:
$(selector).parent(); ele.parentNode
擷取上下節點:
$(selector).prev() //上一個兄弟節點
$(selector).next() //下一個兄弟節點
ele.previousElementSibling || ele.previousSibling
ele.nextElementSibling || ele.nextSibling
刪除節點:
$(selector).remove();parent.removeChild(child);//擷取父節點與子節點,通過父節點刪除子節點
設定屬性:
$(selector).attr(name,value) //設定$(selector).attr(name) //擷取$(selector).removeAttr(name) //刪除ele.setAttribute(name,value);ele.getAttribute(name);ele.removeAttribute(name);
擷取內容:
$(selector).html(); //擷取標籤全部內容,包括標籤$(selector).text();//只擷取文本ele.innerHTML;ele.innerText;
設定css:
$(selector).css({ "color":"white", "height":"300px"});ele.style.height = ‘300px‘;ele.style.cssText = ‘height:300px;color:white;‘
擷取css:
$(selector).css(‘height‘); function getStyle(obj,attrname){ //原生使用方法 if(obj.currentStyle){ return obj.currentStyle[attr]; }else{ return getComputedStyle(obj,null)[attr]; }; };
元素的位置:
$(selector).offset().left; $(selector).offset().top;ele.offsetLeft; ele.offsetTop;
去除字串兩端空白:
$.trim(string); //去除兩端空格 String.prototype.trim = function() { var reExtraSpace = /^\s*(.*?)\s+$/; return this.replace(reExtraSpace, "$1") } /***擴充一下***/ //去除左邊空格 String.prototype.ltrim = function() { return this.replace( /^(\s*| *)/, ""); } //去除右邊空格 String.prototype.rtrim = function() { return this.replace( /(\s*| *)$/, ""); } //替換全部 String.prototype.replaceAll = function(s1, s2) { return this.replace(new RegExp(s1, "gm"), s2) } //去除所有空格,需要配合上面的替換全部 String.prototype.trimAll = function() { var reExtraSpace = /\s*(.*?)\s+/; return this.replaceAll(reExtraSpace, "$1") }
原生與jqueryDOM