How do I adapt this function to function without needing the element ID?

0

I have a function and I want to adapt it to work without needing the element ID ( document.getElementById("slides"); ). I saw that it is possible to do this using the NEW operator, but I had difficulties. Do you have any practical examples that might help?

pg      = 0;
sg      = 20000;
ft      = document.getElementById("slides");
sn      = ft.getElementsByTagName("div");
tt      = sn.length-1;
st      = ["content-slide show-slide", "content-slide"];

//onclick
function slide(i){"proximo"==i&&md_n(),"anterior"==i&&md_p()}

//próximo
function  md_n(){
    if(pg < tt){
        pg=pg+1;
        sn.item(pg).setAttribute("class", st[0]);
        if(pg > 0){
            sn.item(pg-1).setAttribute("class", st[1]);
        }
    }else if(pg > 0 && pg == tt){
        pg=0;
        sn.item(pg).setAttribute("class", st[0]);
        sn.item(tt).setAttribute("class", st[1]);
    }
    console.log("slide: "+pg);
}

//anterior
function md_p(){
    if(pg > 0){
        pg=pg-1;
        sn.item(pg).setAttribute("class", st[0]);
        if(pg > -1){
            sn.item(pg+1).setAttribute("class", st[1]);
        }
    }else if(pg > -1 && pg != tt){
        pg=sn.length-1;
        sn.item(pg).setAttribute("class", st[0]);
        sn.item(pg-(tt)).setAttribute("class", st[1]);
    }
    console.log("slide: "+pg);
}
//play
start = setInterval(function(){md_n()}, sg);
    
asked by anonymous 28.06.2016 / 13:05

2 answers

1

Without the id, one option is to search for the class property. document.getElementsByClassName("nome_da_class"); .

Note that this returns an array, regardless of finding a single element.

Example

var e = document.getElementsByClassName("nome_da_class");
console.log(e[0]); // imprime no console o primeiro que encontrou.

To have everyone you meet, make a loop of repetition

for (var i = 0; i < e.length; i++) {
    console.log(e[i]);
}

Otherwise you would have to read the whole document through all the documents until you find specific properties of the element that looks like tag name, width, height, etc.

Please be aware that I posted only examples, without error handling. For example, at a minimum you should check if something was found, if it did not return false, null or undefined, anyway.

    
28.06.2016 / 13:25
1

In this way you can select elements with the normal css selectors.

querySelector () returns an element (the first one to find), or none (if there is no element with the desired property)

Already querySelectorAll () returns all elements (array) with the property, if any

var heyClass = document.querySelectorAll('.hey')[0]; // primeiro elemento
var heyData = document.querySelector('[data-name="yoo"]'); // primeiro elemento
var spanTag = document.querySelectorAll('span')[0]; // primeiro elemento

console.log(heyClass);
console.log(heyData);
console.log(spanTag);
<div class="hey"></div>
<div data-name="yoo"></div>
<span></span>
    
28.06.2016 / 13:49