Is there a efficient way to save DOM elements in an object variable like this:
.png?
The aim is to preserve some elements of the DOM object in a variable to be able to add attributes.
I can actually go through data- attributes in HTML5 but I prefer a pure JavaScript (JQuery too) solution.
Is there a efficient way to save DOM elements in an object variable like this:
http://img15.hostingpics/pics/357570example.png?
The aim is to preserve some elements of the DOM object in a variable to be able to add attributes.
I can actually go through data- attributes in HTML5 but I prefer a pure JavaScript (JQuery too) solution.
Share Improve this question edited Oct 19, 2014 at 21:24 Bergi 667k161 gold badges1k silver badges1.5k bronze badges asked Oct 19, 2014 at 18:16 TimtimTimtim 3441 gold badge10 silver badges19 bronze badges 03 Answers
Reset to default 2You can simply store a collection of DOM
Elements in a variable.
For example,
var inputs = document.getElementsByTagName("input");
The variable inputs
will contain a live collection of input elements you can refer to later for manipulating.
For example, you can iterate over this collection and add a CSS class using a simple for loop like:
for(var i=0;i<inputs.length;i++){
inputs[i].classList.add("newClass");
}
For setting an attribute, you can use the setAttribute()
method.
You can do the very same in jquery as well, only the syntax for accessing the elements will change.
For example,
var inputs = $("input");
You can iterate over the jQuery object inputs using it's each()
method like
inputs.each(function(){
$(this).addClass("newClass");
});
For setting an attribute to an element using jQuery, you can use it's attr()
method.
Seems to me you are looking for something like this:
var foo = {
p: document.getElementById('some-id'),
h1: document.getElementById('some-other-id')
};
foo.p.data1 = "something";
foo.p.data2 = "something else";
// etc...
The code above saves the elements that have id some-id
and some-other-id
in the fields p
and h1
of the object foo
. It also sets the fields data1
and data2
on foo.p
. The same could be done on foo.h1
.
Note that if some other code seeks the element that has id some-id
that code will see data1
and data2
on the element. That is, the fields your code adds is visible to everyone.
Modern browsers accept adding arbitrary fields on DOM elements. Older browsers won't necessarily accept it. I don't have a list of browser that will allow it and those that won't. I would advise using something more expressive than data1
. In particular such field should be specific enough to avoid a name clash. When I do this, I prefix my field names with the name of my application.
Ok, I found how I could make this, by passing by an object constructor like this :
function objectConstructor( element ) {
this.element = element;
this.data1 = "string";
this.data2 = "string";
}
In any way, thank you for your response.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744967991a4603798.html
评论列表(0条)