[英]How to add class to div depending on url in Javascript?
如何使用純Javascript將類添加到特定頁面上的特定類? 我玩過很多不同的代碼片段,但是無法使任何東西正常工作。 我正在尋找類似以下內容的東西:
<script>
if (window.location.href == 'http://specific-page.com') {
$(somecode).find('existingClass').addClass('newClass');
};
</script>
您可以使用querySelectorAll加上NodeList.forEach() 。
此外,您可以看一下Element.classList方法 。
片段:
// // For test purposes only // window.location.href1 = 'http://specific-page.com'; if (window.location.href1 == 'http://specific-page.com') { document.querySelectorAll('#myDiv .existingClass').forEach(function(ele, idx) { ele.classList.add('newClass'); }); };
.existingClass { height: 30px; background-color: red; } .newClass { border-style: dotted; }
<div id="myDiv"> <p class="existingClass">Thbis is a sample string</p> </div>
它應該工作:
<script>
if (window.location.href == 'http://specific-page.com') {
$('.existingClass').addClass('newClass');
};
</script>
您要做的是將要查找的類用作選擇器,在本例中為".existingClass"
。
還有許多其他方法可以完成此操作,具體取決於您要嘗試獲取的內容。
其他職位:
這是最簡單的方法,但是按類名獲取元素將在某些瀏覽器(如較舊的瀏覽器)上失敗
兼容性可以在這里找到-https: //developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName#Browser_compatibility
// JavaScript Document
window.onload = init;
var divsWithClass = null;
function init() {
if (window.location.href.indexOf("some value you care about") >= 0) {
this.divsWithClass = document.getElementsByClassName("Some Class Name");
var index = 0;
while (index < divsWithClass.length) {
divsWithClass[index].className += " newClass";
index++;
}
}
console.log(divsWithClass);
}
您可以使用setAttribute
將Attribute 類設置為新值。 在該值中,您可以將新類添加到現有的類值中。 另外, getElementsByClassName
返回Elements列表,因此您需要適當地選擇正確的元素。 我在下面的第一個索引處使用元素。
var elements = document.getElementsByClassName("existingClass");
elements[0].setAttribute( "class", "existingClass" + " newClass" );
如果要在Vannila JS中執行此操作,則可以使用下面的代碼。 它不使用jQuery。
if ( window.location.href == 'http://specific-page.com' ) { var el = document.getElementsByClassName("currentClass")[0]; var newClass = el.getAttribute("class"); newClass += " myNewClass"; el.setAttribute("class", newClass) console.log(el) }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.