oscarabilleira
oscarabilleira

Reputation: 181

document.getElementById for different "id" values or alternative to this code

Actually I'm trying to create an "autosave" system for the content of some "" marked as contenteditable.

DIVS have an structure like his.

<div id=test_one contenteditable=true>
<div id=test_other contenteditable=True>
[..]

And there's a function like this, that works fine for only one div (when the user stops writing on a div save the data)

var timeoutId;
document.getElementById('test_one').addEventListener("input", function() {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(function() {    
          function_to_save();    
    }, 1000);
}, false);

The problem is that I try to use this same function for all the divs with a id name that includes the word "test", because all this names are generated dynamically...

I try to use regular expressions what I can't make that work... any idea or alternative code?

Upvotes: 1

Views: 51

Answers (1)

adeneo
adeneo

Reputation: 318312

You could use querySelectorAll to get a nodeList

var elems = document.querySelectorAll("[id*='test']");

and as the question is marked jQuery

var elems = $('[id*='test']');

[id^='test'] will match all ids starting with test.
[id$='test'] will match all ids ending with test.
[id*='test'] will match all ids containing test.

With a nodeList you'd have to iterate

var elems = document.querySelectorAll("[id*='test']");

for (var i=elems.length; i--;) {
    elems[i].addEventListener("input", functionName, false);
}

Upvotes: 1

Related Questions