Run css when loading Javascript CSS page

Asked

Viewed 224 times

0

I am developing a web application and would like to take the edge to the page loading, but it presents following error.

Uncaught TypeError: Cannot set property 'border' of undefined

JS

 <script>

    $(document).ready(function(){

   document.getElementsByClassName("linha").style.border= "0 none";
 });
</script>

CSS

.linha {
border: 1px solid #E0E0DA;
height: 390px;
}

HTML

 <div class="linha">

                <img src="imagens/camisa_1.JPG" alt="camisa1" class="imagem_teste">


    <p class="descricao_produto">Calça Jeans Armani</p>

<h4 class="preco"> A partir de R$134,99</h4>
     <button class="saiba_mais" id="saiba_mais1">SAIBA MAIS</button> 

        </div>

2 answers

2

The function getElementsByClassName returns a list of items that have the specified class, and not only 1. You can try to access the first one for example using [0]:

document.getElementsByClassName("linha")[0].style.border= "0 none";
//---------------------------------------^ aqui

Or if you have several use one for:

for (let linhaHtml of document.getElementsByClassName("linha")){
    linhaHtml.style.border= "0 none";
}

But if you’re already using Jquery, simplify and do:

$(".linha").css("border","0 none");

That works for 1 or more elements without having to differ in the code.

Example:

$(document).ready(function() {
  $(".linha").css("border","0 none");
});
.linha {
  border: 1px solid #E0E0DA;
  height: 390px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="linha">

  <img src="imagens/camisa_1.JPG" alt="camisa1" class="imagem_teste">


  <p class="descricao_produto">Calça Jeans Armani</p>

  <h4 class="preco"> A partir de R$134,99</h4>
  <button class="saiba_mais" id="saiba_mais1">SAIBA MAIS</button>

</div>

Documentation for the function getElementsByClassName

  • has also the querySelector()

  • @Correct Description was another valid alternative, which has even tended to be more scalable and easy to maintain, as it can have any selector other than just class.

0


As you are already using jQuery you set the edge so:

$('.linha').css('border', '0 none');

Browser other questions tagged

You are not signed in. Login or sign up in order to post.