Javascript Onclick work multiple times

0

I need to make a border appear and disappear whenever I click. I can not use jQuery or eventlist. I know I should use IF but I do not know how. What I get so far is to click and make it appear. Must be around the paragraphs. I appreciate your help

 var elements = document.getElementsByTagName("p");
for (var i = 0; i < elements.length; i++){
    elements[i].onclick=function(){
    this.style.border="dashed black 1px";

}

}

    
asked by anonymous 07.10.2017 / 01:55

2 answers

0

Just check if the element has the border

if (this.style.border) {
    this.style.border="";
} else {
    this.style.border="dashed black 1px";
}

Example

var elements = document.getElementsByTagName("p");
for (var i = 0; i < elements.length; i++){
    elements[i].onclick=function(){
      if (this.style.border) {
        this.style.border="";
      } else {
        this.style.border="dashed black 1px";
      }
    }

}
<p>Elemento</p>
<p>Elemento</p>
<p>Elemento</p>
<p>Elemento</p>
<p>Elemento</p>
<p>Elemento</p>
<p>Elemento</p>
<p>Elemento</p>
<p>Elemento</p>
<p>Elemento</p>
<p>Elemento</p>
    
07.10.2017 / 01:58
0

Use css to display the border. So, just use the toggle method to add / remove the class responsible for adding the border.

No JS:

this.classList.toggle('com-borda');

In CSS:

.com-borda {
    border: dashed black 1px;
}
    
07.10.2017 / 02:01