Get multiple IDS, but perform different operations on each of them

Asked

Viewed 105 times

0

I have a function that gets multiple ids at once, but I have to perform slightly different operations in each of them, because of this I end up being forced to create 3 variables for each different id. The idea is that if there is html content in id3, ids 1 and 2 should not be displayed, which leads to another repetition of style.display='none'. I tried to create a variable (var s = s.style.display='none') to simplify the application, but do not know how to apply. My question is whether there is a way to reduce the amount of getElementById from 3 to 1, as well as the style.display='none'., or anything else that reduces the number of repetitions. I thank you in advance for your attention.

function IDs(id1, id2, id3) {

var a = document.getElementById(id1);
var b = document.getElementById(id2);
var c = document.getElementById(id3);

var s = s.style.display='none'; // variável para aplicar estilo

if (a.innerHTML) {
c.style.display='none';
}

else {
a.style.display='none';
b.style.display='none';
 }
}

1 answer

1


Jquery makes it much easier to save code: You can call it any jquery action, like an onclick, for example:

<script>
$(document).ready(function() {
    if($('#id1').html()) {
        $('#id3').hide();
    } else {
        $('#id1').hide();
        $('#id2').hide();
    }
});
</script>

However, to make with pure javascript, it would give to ecomonize code as follows:

<script>
function myHide(id) {
    document.getElementById(id).style.display='none';
}

if (document.getElementById('id1').innerHTML) {
    myHide('id3');
} else {
    myHide('id1');
    myHide('id2');
}
</script>

I hope I helped, hug!

  • Thanks for the help, however, I would like the solution to be in pure Javascript, without the use of Jquery.

  • Eden, I supplemented the answer with what I could imagine to echo code in pure javascript. I also like to "save fingers" and try to make it clearer and readable. Good initiative. Hug

  • It is possible to define document.getElementById(), .innerHTML and .style.display='none' into separate variables, and then put them together, maybe like: id.style, or id+=style, to become document.getElementById(id).style.display='none', and id.inn, or id+=inn to become document.getElementById(id).innerHTML?

  • Everything in its place. getElementById() is a function and returns an object, which in turn has other methods that can be triggered later... .innerHTML is a parameter that contains a string, returns itself. Both can be assigned to other variables. Already `.style.display='None', is an assignment, at most it will return true, indicating success of the operation. I don’t know if I answered, but consider using jQuery, it helps a lot in this work of saving and organizing the code. [s]

Browser other questions tagged

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