简体   繁体   中英

How can I select elements with no id or class?

I am trying to select an element within an element, essentially. The HTML looks something like this:

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <div class="first">
      <div></div>
      <div><!-- the element I want to select --></div>
    </div>
  </body>
</html>

I have tried one method, which looks like this:

function findFirstDescendant(parent, tagname) {
  parent = document.getElementsByClassName(parent)[0];
  var descendants = parent.getElementsByTagName(tagname);
  if (descendants.length)
    return descendants[0];
  return null;
}

and also this:

document.getElementsByClassName("first")[0].getElementsByTagName("div")[1];

Neither work, as the method seems to be outdated. I would like to keep jQuery out of this, but it is acceptable if there is no other solution.

You should definitely use querySelector to take advantage of CSS selectors...

 var el = document.querySelector('.first > div:nth-child(2)'); console.log(el); 
 <!DOCTYPE html> <html> <head></head> <body> <div class="first"> <div></div> <div>Hello!</div> </div> </body> </html> 

But obviously, you can use this more classical solution too:

 var el = document.getElementsByClassName('first')[0].getElementsByTagName('div')[1]; console.log(el); 
 <!DOCTYPE html> <html> <head></head> <body> <div class="first"> <div></div> <div>Hello!</div> </div> </body> </html> 

Sorry for wasting anyone's time. I feel a little dumb for not thinking of this sooner. I fixed the problem by adding a 250ms delay to the script, as it was being executed before the page fully loaded. My code was similar to this:

setTimeout(function() {
  var a = document.getElementsByClassName("card-player")[0].getElementsByTagName("div")[0];
  console.log(a);
}, 250);

You could also add in more variables if you wanted to debug or log more information like this:

setTimeout(function() {
  var a = document.getElementsByClassName("first")[0];
  var b = a.getElementsByTagName("div")[1];
  var c = b.getElementsByTagName("div")[1];
  var d = b.getElementsByTagName("div")[2];
}, 250);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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