Check if Div with specific Class exists in the page

后端 未结 3 1857
闹比i
闹比i 2021-01-27 20:09

I\'m trying to modify an existing webpage by inserting my own Javascript file in it. I\'m setting a background Image for this webpage by inserting a new Div through my Javascrip

相关标签:
3条回答
  • 2021-01-27 20:54

    If you load the jQuery library in your page, which you can link from the Google CDN, this is a very simple matter.

    CDN: https://developers.google.com/speed/libraries/devguide#jquery

    Usage: $("div.className").first()

    Otherwise this will require some more effort ... the best possible way to deal with this is add an id attribute to the div element like so:

    <div id="myElement"></div>
    

    And then use the document.getElementById function to retrieve your div tag.

    document.getElementById('myElement');
    

    To see if it has a specific class after this addition please refer to this other post: Test if an element contains a class?

    0 讨论(0)
  • 2021-01-27 21:03

    You'd have to loop through all of the <div> elements on the page, until one matches the className you are looking for. Something like:

    var div = document.getElementsByTagName('div');
    for(i=0; i<div.length; i++) {
        if(div[i].className.match(/(^|\s)ie(\s|$)/)) {
    
            // Code to Do your IE Stuff Here
    
            break;
        }
    }
    
    0 讨论(0)
  • 2021-01-27 21:07
    document.addEventListener("DOMContentLoaded", function() {
      var ie = document.getElementsByClassName("ie");
      if(ie.length > 0) {
        alert("It's IE!");
      }
    }
    

    This should answer your first question, although I agree that there are better solutions for your overall goal.

    0 讨论(0)
提交回复
热议问题