Jona
Jona

Reputation: 45

Reset Border style

I have a image that is currently being styled with Jquery once it's clicked. I eventually hide it in Javascript. I want to reshow it, but I want it to have the border removed.

Here is HTML:

<div id="playOptionsWager" style="display: none">
    <h4>Choose your move to beat the computer!</h4>
    <img id="clickedRockWager" src="img/rock.jpg" onclick="playWagerRock()" />
    <img id="clickedPaperWager" src="img/paper.jpg" onclick="playWagerPaper()"/>
    <img id="clickedScissorsWager" src="img/scissors.jpg" onclick="playWagerScissors()" />
</div>

Jquery:

$(function () {
    $("img").on("click",function() {
        $(this).siblings().css('border','0px')
        $(this).css('border', "solid 2px red");
    });
});

Here is what I was trying in Javascript:

function autobet() {
    coinBalance -= currentBet*2;
    alert(getBalance());
    document.getElementsByTagName("IMG").style.border="";
}

However when it reshows the div it has the border on it still.

Thanks for the help!

Upvotes: 0

Views: 768

Answers (3)

Nick Parsons
Nick Parsons

Reputation: 50884

Your issue is that document.getElementsByTagName("IMG") returns a collection of elements, so simply applying .style.border on this collection won't work. Instead, you need to loop over this collection, and set every image within it to have no border using .style.border = 0;:

See working example (with div) below:

function removeBorder() {
  [...document.getElementsByTagName("div")].forEach(elem => {
    elem.style.border = 0;
  });
}
.box {
  height: 100px;
  width: 100px;
  background: black;
  display: inline-block;
}

.active {
  border: 3px solid red;
}
<div class="box"></div>
<div class="box active"></div>
<div class="box"></div>

<br />
<button onclick="removeBorder()">Remove border</button>

Also note that [...document.getElementsByTagName("IMG")] is a way of converting the collection of elements into an array of elements, which thus allows us to use the .forEach method to loop over it.

Upvotes: 2

barstromza
barstromza

Reputation: 77

First you need to iterate over the collection of html elements you have - when using getElementsByTagName you get back an array of elements. Second you need to give the elements a style of zero.

const divElements = document.getElementsByTagName("IMG");
for (let i=0; i < divElements.length; i++) {
  divElements[i].style.border = 0;
}

You can see the code on stackbliz - https://stackblitz.com/edit/border-issue?file=index.js

Upvotes: -1

Ibu
Ibu

Reputation: 43850

You started with jQuery, let's continue with jQuery.

function autobet() {
    coinBalance -= currentBet*2;
    alert(getBalance());
    $("img").css("border","");
}

The problem is that getElementsByTagName() returns a collection not one element.

Upvotes: 0

Related Questions