-1

I would like to change the style, if there is a specific class on the page, but it doesn't work. what is wrong with below code snippet?

https://jsfiddle.net/1wc0xdor/

<html>
<body>
<div id='category'>
     <div id="search_filters_wrapper">
      Filter
      </div>  
      <div class="st_banner_row" style="">
       There is Banner
      </div>
</div>
</body>
</html>



<script>
var elementExists =  document.getElementById('category').getElementsByClassName('st_banner_row');
if (typeof(elementExists) != 'undefined' && elementExists != null)
{
     $("#search_filters_wrapper").css({
          margin-top: 40,
       });

}
</script>
Jeet
  • 5,569
  • 8
  • 43
  • 75
zharf pzh
  • 75
  • 1
  • 8
  • 1
    For starters you forgot to include jQuery. Second you used a `#` in your ID which you probably didn't want to do (`
    `). Third, you forgot to put quotes around `none`. Finally, your jsFiddle code is different from the code in your question. Fix all the typos and discrepancies and it seems to work https://jsfiddle.net/j08691/rLaqb072/
    – j08691 Oct 14 '19 at 17:21
  • 2
    `getElementsByClassName` always returns a `NodeList`, not `undefined` or `null`. – Barmar Oct 14 '19 at 17:23
  • Possible duplicate of [What do querySelectorAll and getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) –  Oct 14 '19 at 17:27

3 Answers3

2

document.getElementsByClassName returns a NodeList. If the class isn't found, it will return an empty list, not null.

Check the length rather than whether it's null.

Also, margin-top is not a valid identifier, you need to quote it to use it as an object key (or you can change to camelCase marginTop:)

if (elementExists.length != 0) {
    $("#search_filters_wrapper").css({
        "margin-top": 40,
    });
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

getElementsByClassName always returns a NodeList (think, array), so elementExists always... exists. So you really only need to check if the array isn't empty to be sure that your target class exists. Further, rather than calling getElementById first, you really only need to call getElementsByClassName, unless you're specifically looking for this class within the scope of the parent element with that id.

If you do need to search within the scope of the parent element with that id, consider using querySelectorAll with an appropriate CSS selector

const elements = document.querySelectorAll('#category .st_banner_row');
if (elements.length) {
    $('#search_filters_wrapper').css({
        'margin-top': 40
    });
}

Also, consider setting a CSS class here rather than programmatically setting the css attribute directly, as the latter is bad practice unless it can't be helped.

Thomas Preston
  • 697
  • 1
  • 7
  • 19
0

Answer:

When you check if the element exists you are actually looking at an Array. To determine if the Array is not empty, and therefore, the class exists within the category element, you just need to test the length property.

If the Array length is 0 and nothing is in it, it will return false. If the Array length is greater than 0, something is in it, and it will return true.

Secondly when you utilize properties that have a hyphen( - ) you need to pass that property as a String within the object you're passing to the css method of JQuery's element wrapper.

var elementExists = document.getElementById('category')
                    .getElementsByClassName('st_banner_row')
                    .length;
if (elementExists)
{
     $("#search_filters_wrapper").css({"margin-top": 40});

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='category'>
<span>Below is 40px</span>
     <div id="search_filters_wrapper">
      Filter
      </div>  
      <div class="st_banner_row" style="">
       There is Banner
      </div>
</div>

Aside:

It's odd that you're using JQuery for this one aspect of code. It would be easier and more maintainable to use either all Vanilla JavaScript or all JQuery.


JQuery:

var elementExists = $("#category").find(".st_banner_row").length;
if (elementExists)
{
     $("#search_filters_wrapper").css({"margin-top": 40});

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='category'>
<span>Below is 40px</span>
     <div id="search_filters_wrapper">
      Filter
      </div>  
      <div class="st_banner_row" style="">
       There is Banner
      </div>
</div>

JavaScript:

var elementExists = document.getElementById('category')
                    .getElementsByClassName('st_banner_row')
                    .length;
if (elementExists)
{
     document.getElementById("search_filters_wrapper").style.marginTop = "40px";

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='category'>
<span>Below is 40px</span>
     <div id="search_filters_wrapper">
      Filter
      </div>  
      <div class="st_banner_row" style="">
       There is Banner
      </div>
</div>

Alternative Vanilla JS using querySelector:

var elementExists = document.querySelector('#category .st_banner_row');
if (elementExists)
{
     document.querySelector("#search_filters_wrapper").style.marginTop = "40px";

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='category'>
<span>Below is 40px</span>
     <div id="search_filters_wrapper">
      Filter
      </div>  
      <div class="st_banner_row" style="">
       There is Banner
      </div>
</div>

Note In this version we don't need to check the length because if category does not have a child with a class of st_banner_row the selector will return undefined.


Alternative Vanilla JavaScript Functional example:

// helper functions
const el = ( query, context = document ) => context.querySelector( query ),
 elementExists = query => Boolean( el( query ) ),
 ifElementExists = ( query, fn = () => undefined ) => elementExists( query ) && fn(),
 elStyle = query => ( prop, value ) => el( query ).style[ prop ] = value,
 changeStyle = query => ( prop, value ) => () => elStyle( query )( prop, value );


// execution
ifElementExists( "#category .st_banner_row", 
    changeStyle( "#search_filters_wrapper" )( "margin-top", "40px" ) 
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='category'>
  <span>Below is 40px</span>
  <div id="search_filters_wrapper">
    Filter
  </div>
  <div class="st_banner_row" style="">
    There is Banner
  </div>
</div>
zfrisch
  • 8,474
  • 1
  • 22
  • 34