1

I am trying to find a specific div with class using pure javascript but its not giving me result, so I need advise of experts. Here is my html

<div class="search">
<center><h1>Search Content</h1></center>
</div>

This is the javascript code I am trying;

  if(document.div.className.match('search')){
     console.log("Found");
  } else {
     console.log("Not Found");
     }

I tried using .classList but it's not supported on IE.10 , so is there any way I can find my required output using pure js?

Here is demo -> https://jsfiddle.net/05aj58nj/

user3550203
  • 699
  • 1
  • 7
  • 15
  • If you are trying to find a specific element, you shouldn't use classes but ids instead. – MinusFour Dec 20 '15 at 18:26
  • @MinusFour actually the id is not available, I only have class available, and unfortunately I don't have access to add id there :( – user3550203 Dec 20 '15 at 18:32
  • That's fine really. It's just that there's nothing unique about a `div` with a specific class, so you might end up selecting the wrong `div` if you have multiples matches. – MinusFour Dec 20 '15 at 18:35

3 Answers3

4

The more common way is to use

document.getElementsByClassName("search");

I find this to be more descriptive and clear.

christopher
  • 26,815
  • 5
  • 55
  • 89
  • This will select all elements though including non divs. – MinusFour Dec 20 '15 at 18:23
  • the only one thing with this method is remember that it returns `array` of elements with such class – Andrew Dec 20 '15 at 18:24
  • Actually, @Andrew is incorrect. The method returns an HTMLCollection rather than an array. There are important differences between those two objects, and you may want to convert the result to a real array before processing it. But if you just want the first match, then `[0]` will work just fine. – Stephen Thomas Dec 20 '15 at 18:29
3

Can you try: document.querySelectorAll? This is the right way to do it using Pure JavaScript.

document.querySelectorAll("div.search")[0];
document.getElementsByClassName("search")[0];

In the getElementsByClassName you can check if the type of the element is a <div>.

<h3 class="search">Head</h3>
<div class="search">Item 1</div>
<div class="search">Item 2</div>
<script>
  a = document.getElementsByClassName("search");
  for (i = 0; i < a.length; i++)
    if (a[i].localName.toLowerCase == "div")
      console.dir(a[i]);
</script>
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

document.getElementsByClassName('classname')

...or...

document.querySelectorAll('.classname')

getElementsByClassName will return an HTMLCollection, but querySelectorAll will return a NodeList. If you ever need to iterate over any of them, you can use this convert them to arrays.

Array.prototype.slice.apply( document.querySelectorAll('.classname') )

birdoftheday
  • 816
  • 7
  • 13