Selection of elements based on class type and element

How can I select all elements in an HTML document with a specific class and specific element type?

I am trying to select all the class anchors title loggedinfrom an HTML document (and then open them in a browser). They are inside the class paragraphs title.

They are leaves in the following DOM tree:

+ body
  + div class='content'
    + div id='siteTable' class='sitetable linklisting'
      + div class='thing id-t3_xxxx xxx xxx link'
        + div class='entry unvoted'
            + p class='title'
              + a class='title loggedin '

Where xindicates the contents of the variable.

(I want to do this in raw JavaScript, i.e. not in jQuery.)

+3
source share
4 answers

Try the following:

var aElems = document.getElementsByTagName("a");
for (var i=0; i<aElems.length; ++i) {
    var classesArr = aElems[i].className.split(/\s+/),
        classesObj = {};
    for (var j=0; j<classesArr.length; ++j) {
        classesObj[classesArr[i]] = true;
    }
    if (classesObj.hasOwnProperty("title") && classesObj.hasOwnProperty("loggedin")) {
        // action
    }
}

Some explanation:

  • document.getElementsByTagNamereturns an array of elements of this type (in this case a)
  • (. aElems[i].className.split)
  • (. aElems[i].className.split)
+6

, , : title loggedin. document.getElementsByClassName() .

var elements = document.getElementsByClassName("title loggedin");

.

+3

document.getElementsByTagName() . className ( title loggedin).

, JavaScript; , jQuery Prototype.

+2

I know this is an old question, but if you ever wanted to know how jQuery selects elements, you can look at the source of their autonomous selection mechanism Sizzle.js , which over the years was developed by many smart people who have spent a lot of time on performance:)

+1
source

Source: https://habr.com/ru/post/1744759/


All Articles