简体   繁体   English

如果对象具有特定的CSS类,请使用本机JavaScript更改对象的title属性

[英]Using Native JavaScript, change the title attribute of an object if it has a certain CSS class

So by using native javascript, how would I go about saying "if this object has this css class, add this to the title attribute" 因此,通过使用本机javascript,我将如何说“如果此对象具有此CSS类,请将其添加到title属性”

document.addEventListener("DOMContentLoaded", function(event) { 
    if(element.classlist.contains("current_page_item")||element.classlist.contains("current-page-ancestor")){

    }
});

That is as far as I've gotten, I'm trying to stick to native javascript just so we don't have to load up any libraries and can keep the site as minimalist as possible. 据我所知,我试图坚持使用本机javascript,以便我们不必加载任何库,并且可以使网站尽可能地简约。

You can use getElementsByClassName() 您可以使用getElementsByClassName()

var x = document.getElementsByClassName("current_page_item");

Then loop and add title 然后循环并添加标题

x.forEach(function(element){
   element.title = "title";
});

or 要么

for (var i = 0; i < x.length; i++) {
    x[i].title ="title";
}

To answer to your comment, to apply the title to the "a" element that is a child of the div element that has the "current_page_item" class 要回答您的评论,请将标题应用于“ a”元素,该元素是具有“ current_page_item”类的div元素的子元素

for (var i = 0; i < x.length; i++) {
    var y = x[i].getElementsByTagName("a");
    y[0].title = "title";
}

Similar to Rohit Shetty's reply, you could also use the querySelector: 与Rohit Shetty的回复类似,您也可以使用querySelector:

let elements = document.querySelector(".current_page_item");
elements.forEach(function(e) {
  e.title = "title";
);

You can use getElementsByClassName() 您可以使用getElementsByClassName()

var x = document.getElementsByClassName("current_page_item");
for(var i=0;i<x.length;i++){
    x[i].title += "BLAH";
}

I don't now if I have understood well. 如果我了解得很好,我现在就不知道。

But let's try. 但是,让我们尝试。 First, locate the elements. 首先,找到元素。

const nodes = document.querySelectorAll('.current_page_item, .current_page_item')
// nodes are the elements of one of the classes names

Then, apply the class Names to title. 然后,将“名称”类应用于标题。

function containsOfTheClasses (node) {
    return classNames.some(x => node.classList.contains(x))
}

nodes.forEach(function (node) {
    node.title += classNames.filter(containsOfTheClasses).join(' ')
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM