如何刪除所有DOM元素與特定的類名或元件寬度的ID與特定模式啓動。像(沒有任何框架!)除去所有的DOM元素與特定的className
id="selectbox1"
id="selectbox2"
id="selectbox3"
id="selectbox4"
感謝
如何刪除所有DOM元素與特定的類名或元件寬度的ID與特定模式啓動。像(沒有任何框架!)除去所有的DOM元素與特定的className
id="selectbox1"
id="selectbox2"
id="selectbox3"
id="selectbox4"
感謝
你不得不使用getElementsByTagName(*)
遍歷整個集合,正則表達式檢查.className
財產/\bYourClasName\b/
(類名可以有更多的比一個類,由一個空格分隔),然後還檢查元素的.id
屬性與另一個正則表達式:/^IDStartsWithThis/
最後在任何匹配,你將不得不打電話element.parentNode.removeChild(element);
(在我的工作方式,並在匆忙,如果你需要更多的代碼,我可以提供一次我到那裏周圍630 EST)
編輯:下面的代碼:
用法:removeElemIf(idStartsWith,containsClass)
。你可以通過空,只有ID(第二個參數是不確定的),空格(空格將被忽略,這兩個參數都經修整的第一)。大小寫對兩個參數都不敏感。
function removeElemIf(theID, theClass) { /* class => full match, id => startswith */
checkID = !(theID === undefined || theID === null || (theID = theID.replace(/^\s*|\s*$/g, '')).length == 0);
checkClass = !(theClass === undefined || theClass === null || (theClass = theClass.replace(/^\s*|\s*$/g, '')).length == 0);
if (!(checkID || checkClass)) return;
var oBody = document.getElementsByTagName('body')[0]; // only search the body
var oElems = oBody.getElementsByTagName('*'); // get all the elements within body
for (i = oElems.length - 1; i >= 0; i--) { // loop through backwards in case of delete
el = oElems[i]; // set current element
found = false; // reset flag
if (checkID) { /* check the ID for starting with "theID", originally used indexOf but its case sensitive*/
re = new RegExp('^'+theID,'i');
if (el.id.match(re)) found = true;
}
if (!found && checkClass) { /* only test class if the id doesn't match,
save the regex in instances where the
class names are long or many*/
re = new RegExp('\\b' + theClass + '\\b', 'i');
if (el.className.match(re)) found = true;
}
if (found) el.parentNode.removeChild(el); /* if found, remove from parent */
}
}
遍歷DOM樹,對比較發現每種元素的className
財產。是的,這很乏味,但這是如何完成的。您可以以遞歸方式或迭代方式遍歷。第一個是最容易編寫的,但第二個有更好的性能。
看到這個SO螺紋: jQuery matching pattern
,並檢查了getElementsByTagName()功能
請考慮增加一個評論,如果你認爲這個帖子可以提高;-) – helle 2010-11-01 08:45:49
沒有jQuery的?祝你好運。 :)它可以完成,但將需要大量的循環和正則表達式。 BTW - ID應該是唯一的一個頁面。 – RPM1984 2010-11-01 08:38:15
你對框架有什麼異議?如果你不想要,它將使事情變得更加簡單,並且不必在項目的其他任何地方使用它。 – Jan 2010-11-01 09:07:57
你們怎麼了?你用jQuery被洗腦了嗎?在這個例子中'id's'是獨一無二的(他寫的是從頭開始)。通過很多循環,你的意思是1單循環?來吧。它甚至不需要Regex,一個'indexOf'就可以做到。 – galambalazs 2010-11-01 09:16:22