Override HTML DOM element methods JS
Short question:
How may I override DOM built-in function as document.getElementById ()
or build my own method, in pure JS?
Explanations:
I am working on an API which uses attributes to locate divs in my HTML page.
I can get the attributes of a div using this method:
for (var att, i = 0, atts = div.attributes, n = atts.length; i < n; i++) {
att = atts[i];
nodeName = att.nodeName;
nodeValue = att.nodeValue;
}
Then, I need to use this code to check the attributes of a given HTML object. I built a method which checks the document's div's attributes:
document.getElementByIdentifier = function (identifier) {
for (var i = 0; i < this.children.length; i++) {
for (var att, i = 0, atts = div.attributes, n = atts.length; i < n; i++) {
att = atts[i];
nodeName = att.nodeName;
nodeValue = att.nodeValue;
// Here I check the attributes
}
}
}
However, I can not call this function from an HTML Dom object (except, here, the document
object). I do not find how to replace document
by something like allHTMLElements
in my method above. The goal is to have the same freedom of usage as document.getElementById
for example.
How may I do that?
Note: I am very surprised because the document.getElementById
seems to be located into the document
object. However, when I try to build my own method into this object, it does not work. Why?
Other note: This is (at least for me) an HTML DOM object:var A = document.getElementById ("C");
. Here the object A is an HTML Dom object calls: "object" by google chrome when I try console.log (typeof A);
.
Otherwise note:
This is an example of one of my divs:
<script identifier="OAdgRzf"></script>
Finally note:
Use document.querySelector
is the way I am already using on my library. However, I now have to run updates and tests for elements which are called by the user. I built a function which uses document.querySelector
and then runs tests but it is not very pretty.
Tell me a comment if you have some questions.
javascript dom
|
show 7 more comments
Short question:
How may I override DOM built-in function as document.getElementById ()
or build my own method, in pure JS?
Explanations:
I am working on an API which uses attributes to locate divs in my HTML page.
I can get the attributes of a div using this method:
for (var att, i = 0, atts = div.attributes, n = atts.length; i < n; i++) {
att = atts[i];
nodeName = att.nodeName;
nodeValue = att.nodeValue;
}
Then, I need to use this code to check the attributes of a given HTML object. I built a method which checks the document's div's attributes:
document.getElementByIdentifier = function (identifier) {
for (var i = 0; i < this.children.length; i++) {
for (var att, i = 0, atts = div.attributes, n = atts.length; i < n; i++) {
att = atts[i];
nodeName = att.nodeName;
nodeValue = att.nodeValue;
// Here I check the attributes
}
}
}
However, I can not call this function from an HTML Dom object (except, here, the document
object). I do not find how to replace document
by something like allHTMLElements
in my method above. The goal is to have the same freedom of usage as document.getElementById
for example.
How may I do that?
Note: I am very surprised because the document.getElementById
seems to be located into the document
object. However, when I try to build my own method into this object, it does not work. Why?
Other note: This is (at least for me) an HTML DOM object:var A = document.getElementById ("C");
. Here the object A is an HTML Dom object calls: "object" by google chrome when I try console.log (typeof A);
.
Otherwise note:
This is an example of one of my divs:
<script identifier="OAdgRzf"></script>
Finally note:
Use document.querySelector
is the way I am already using on my library. However, I now have to run updates and tests for elements which are called by the user. I built a function which uses document.querySelector
and then runs tests but it is not very pretty.
Tell me a comment if you have some questions.
javascript dom
1
Just out of curiousity, why would you want to build a custom method for something that is already there as a built-in function?.
– AndrewL
Dec 28 '18 at 17:48
Just wondering, why do you need to do your own method, woulddocument.querySelectors
not work for you?
– Pytth
Dec 28 '18 at 17:49
@AndrewL, My library uses a special attribute to locates divs. This attribute cannot be found with a built-in method (or at least I do not know it). I need to create a built-in method to make easily the interaction user-library.
– SphynxTech
Dec 28 '18 at 17:50
document.querySelector('[whateverAttributeYouHave]')
will find any element with whatever attribute
– Taplar
Dec 28 '18 at 17:52
2
document.querySelector('div[special-attribute="potatoSalad"]')
querySelector( as mentioned by @Pytth ) should let you query by special attributes of your divs. It's always dicey to hack core functionality.
– Doug
Dec 28 '18 at 17:52
|
show 7 more comments
Short question:
How may I override DOM built-in function as document.getElementById ()
or build my own method, in pure JS?
Explanations:
I am working on an API which uses attributes to locate divs in my HTML page.
I can get the attributes of a div using this method:
for (var att, i = 0, atts = div.attributes, n = atts.length; i < n; i++) {
att = atts[i];
nodeName = att.nodeName;
nodeValue = att.nodeValue;
}
Then, I need to use this code to check the attributes of a given HTML object. I built a method which checks the document's div's attributes:
document.getElementByIdentifier = function (identifier) {
for (var i = 0; i < this.children.length; i++) {
for (var att, i = 0, atts = div.attributes, n = atts.length; i < n; i++) {
att = atts[i];
nodeName = att.nodeName;
nodeValue = att.nodeValue;
// Here I check the attributes
}
}
}
However, I can not call this function from an HTML Dom object (except, here, the document
object). I do not find how to replace document
by something like allHTMLElements
in my method above. The goal is to have the same freedom of usage as document.getElementById
for example.
How may I do that?
Note: I am very surprised because the document.getElementById
seems to be located into the document
object. However, when I try to build my own method into this object, it does not work. Why?
Other note: This is (at least for me) an HTML DOM object:var A = document.getElementById ("C");
. Here the object A is an HTML Dom object calls: "object" by google chrome when I try console.log (typeof A);
.
Otherwise note:
This is an example of one of my divs:
<script identifier="OAdgRzf"></script>
Finally note:
Use document.querySelector
is the way I am already using on my library. However, I now have to run updates and tests for elements which are called by the user. I built a function which uses document.querySelector
and then runs tests but it is not very pretty.
Tell me a comment if you have some questions.
javascript dom
Short question:
How may I override DOM built-in function as document.getElementById ()
or build my own method, in pure JS?
Explanations:
I am working on an API which uses attributes to locate divs in my HTML page.
I can get the attributes of a div using this method:
for (var att, i = 0, atts = div.attributes, n = atts.length; i < n; i++) {
att = atts[i];
nodeName = att.nodeName;
nodeValue = att.nodeValue;
}
Then, I need to use this code to check the attributes of a given HTML object. I built a method which checks the document's div's attributes:
document.getElementByIdentifier = function (identifier) {
for (var i = 0; i < this.children.length; i++) {
for (var att, i = 0, atts = div.attributes, n = atts.length; i < n; i++) {
att = atts[i];
nodeName = att.nodeName;
nodeValue = att.nodeValue;
// Here I check the attributes
}
}
}
However, I can not call this function from an HTML Dom object (except, here, the document
object). I do not find how to replace document
by something like allHTMLElements
in my method above. The goal is to have the same freedom of usage as document.getElementById
for example.
How may I do that?
Note: I am very surprised because the document.getElementById
seems to be located into the document
object. However, when I try to build my own method into this object, it does not work. Why?
Other note: This is (at least for me) an HTML DOM object:var A = document.getElementById ("C");
. Here the object A is an HTML Dom object calls: "object" by google chrome when I try console.log (typeof A);
.
Otherwise note:
This is an example of one of my divs:
<script identifier="OAdgRzf"></script>
Finally note:
Use document.querySelector
is the way I am already using on my library. However, I now have to run updates and tests for elements which are called by the user. I built a function which uses document.querySelector
and then runs tests but it is not very pretty.
Tell me a comment if you have some questions.
javascript dom
javascript dom
edited Dec 28 '18 at 18:17
SphynxTech
asked Dec 28 '18 at 17:46
SphynxTechSphynxTech
1,021825
1,021825
1
Just out of curiousity, why would you want to build a custom method for something that is already there as a built-in function?.
– AndrewL
Dec 28 '18 at 17:48
Just wondering, why do you need to do your own method, woulddocument.querySelectors
not work for you?
– Pytth
Dec 28 '18 at 17:49
@AndrewL, My library uses a special attribute to locates divs. This attribute cannot be found with a built-in method (or at least I do not know it). I need to create a built-in method to make easily the interaction user-library.
– SphynxTech
Dec 28 '18 at 17:50
document.querySelector('[whateverAttributeYouHave]')
will find any element with whatever attribute
– Taplar
Dec 28 '18 at 17:52
2
document.querySelector('div[special-attribute="potatoSalad"]')
querySelector( as mentioned by @Pytth ) should let you query by special attributes of your divs. It's always dicey to hack core functionality.
– Doug
Dec 28 '18 at 17:52
|
show 7 more comments
1
Just out of curiousity, why would you want to build a custom method for something that is already there as a built-in function?.
– AndrewL
Dec 28 '18 at 17:48
Just wondering, why do you need to do your own method, woulddocument.querySelectors
not work for you?
– Pytth
Dec 28 '18 at 17:49
@AndrewL, My library uses a special attribute to locates divs. This attribute cannot be found with a built-in method (or at least I do not know it). I need to create a built-in method to make easily the interaction user-library.
– SphynxTech
Dec 28 '18 at 17:50
document.querySelector('[whateverAttributeYouHave]')
will find any element with whatever attribute
– Taplar
Dec 28 '18 at 17:52
2
document.querySelector('div[special-attribute="potatoSalad"]')
querySelector( as mentioned by @Pytth ) should let you query by special attributes of your divs. It's always dicey to hack core functionality.
– Doug
Dec 28 '18 at 17:52
1
1
Just out of curiousity, why would you want to build a custom method for something that is already there as a built-in function?.
– AndrewL
Dec 28 '18 at 17:48
Just out of curiousity, why would you want to build a custom method for something that is already there as a built-in function?.
– AndrewL
Dec 28 '18 at 17:48
Just wondering, why do you need to do your own method, would
document.querySelectors
not work for you?– Pytth
Dec 28 '18 at 17:49
Just wondering, why do you need to do your own method, would
document.querySelectors
not work for you?– Pytth
Dec 28 '18 at 17:49
@AndrewL, My library uses a special attribute to locates divs. This attribute cannot be found with a built-in method (or at least I do not know it). I need to create a built-in method to make easily the interaction user-library.
– SphynxTech
Dec 28 '18 at 17:50
@AndrewL, My library uses a special attribute to locates divs. This attribute cannot be found with a built-in method (or at least I do not know it). I need to create a built-in method to make easily the interaction user-library.
– SphynxTech
Dec 28 '18 at 17:50
document.querySelector('[whateverAttributeYouHave]')
will find any element with whatever attribute– Taplar
Dec 28 '18 at 17:52
document.querySelector('[whateverAttributeYouHave]')
will find any element with whatever attribute– Taplar
Dec 28 '18 at 17:52
2
2
document.querySelector('div[special-attribute="potatoSalad"]')
querySelector( as mentioned by @Pytth ) should let you query by special attributes of your divs. It's always dicey to hack core functionality.– Doug
Dec 28 '18 at 17:52
document.querySelector('div[special-attribute="potatoSalad"]')
querySelector( as mentioned by @Pytth ) should let you query by special attributes of your divs. It's always dicey to hack core functionality.– Doug
Dec 28 '18 at 17:52
|
show 7 more comments
2 Answers
2
active
oldest
votes
To repeat what's going on up in the comments; please, please, PLEASE, do not try and hack core functionality. If you would like to create a custom method to use in your code you can extend the Object
object...
Object.prototype.getEl = function( selector ){
return document.querySelector( `[special-attribute="${selector
}"]` );
}
console.log( document.getEl('potatoSalad') );
<div special-attribute="potatoSalad">one two three</div>
This way you can have the more condensed call document.getEl()
to target your desired elements while still preserving the original methods in JavaScript.
It may be possible to hack the core code; but it is very strongly recommended to not attempt this. As everyone discovers when they go down this path, it normally results in unexpected errors in the code -- where things are connected and it was not immediately known.
It is exactly what I need! Thank you for your work! I also code in C++ where it is quite common to override built-in functions, I thought I can do the same thing in JS. Thank you!
– SphynxTech
Dec 30 '18 at 16:13
add a comment |
This attribute cannot be found with a built-in method (or at least I
do not know it)
Yes there is a built-in method for finding special attributes and that method is called querySelector or if you want to retrieve more than one object, there is querySelectorAll that will return a list (called NodeList) of the document's elements that match the specified group of selectors.
Assuming you have a div with the attribute someWeirdAttribute
like this:
<div someWeirdAttribute="someWeirdValue">
Hello World
</div>
You can find the above element like this:
document.querySelector('[someWeirdAttribute="someWeirdValue"]');
Or if you want a more practical example, let us retrieve the attribute value as well as the div content from the above in this jsFiddle or in the code snippet below:
/* JavaScript */
var div = document.querySelector('[someWeirdAttribute="someWeirdValue"]');
var output = document.getElementById('info');
var btn = document.querySelector('button');
btn.addEventListener('click', function(){
var attrVal = div.getAttribute('someWeirdAttribute');
var divContent = div.textContent;
console.log(attrVal);
output.innerHTML = '';
output.innerHTML += `<p>The div atrribute value of <strong>someWeirdAttribute</strong> is <strong>${attrVal}</strong></p>
<p>The content inside the div is <strong>${divContent}</strong></p>`
})
<!-- HTML -->
<div someWeirdAttribute="someWeirdValue">
Hello World
</div>
<hr>
<button>
Get info about above element
</button>
<div id="info"></div>
1
A handy dandy thing I like to do with the defaultquerySelector
andquerySelectorAll
is to make shortcuts to them:var _ = document.querySelector.bind(document);
This makesdocument.querySelector(...)
become_(...)
.
– Marcus Parsons
Dec 28 '18 at 18:19
1
@MarcusParsons That is a really simple yet nice trick to use especially if there are a lot of variable assignments I have to make. It also makes the variable assignment section of my JS look cleaner. I honestly never thought of doing that before.Thanks for the tip man!! Will definitely start implementing this now.
– AndrewL
Dec 28 '18 at 18:22
1
Absolutely! I forgot to mentiondocument.querySelectorAll
as well. My assignment for that is usually:var __ = document.querySelectorAll.bind(document);
which of course makesdocument.querySelectorAll(...)
become__(...)
– Marcus Parsons
Dec 28 '18 at 18:25
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53962381%2foverride-html-dom-element-methods-js%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
To repeat what's going on up in the comments; please, please, PLEASE, do not try and hack core functionality. If you would like to create a custom method to use in your code you can extend the Object
object...
Object.prototype.getEl = function( selector ){
return document.querySelector( `[special-attribute="${selector
}"]` );
}
console.log( document.getEl('potatoSalad') );
<div special-attribute="potatoSalad">one two three</div>
This way you can have the more condensed call document.getEl()
to target your desired elements while still preserving the original methods in JavaScript.
It may be possible to hack the core code; but it is very strongly recommended to not attempt this. As everyone discovers when they go down this path, it normally results in unexpected errors in the code -- where things are connected and it was not immediately known.
It is exactly what I need! Thank you for your work! I also code in C++ where it is quite common to override built-in functions, I thought I can do the same thing in JS. Thank you!
– SphynxTech
Dec 30 '18 at 16:13
add a comment |
To repeat what's going on up in the comments; please, please, PLEASE, do not try and hack core functionality. If you would like to create a custom method to use in your code you can extend the Object
object...
Object.prototype.getEl = function( selector ){
return document.querySelector( `[special-attribute="${selector
}"]` );
}
console.log( document.getEl('potatoSalad') );
<div special-attribute="potatoSalad">one two three</div>
This way you can have the more condensed call document.getEl()
to target your desired elements while still preserving the original methods in JavaScript.
It may be possible to hack the core code; but it is very strongly recommended to not attempt this. As everyone discovers when they go down this path, it normally results in unexpected errors in the code -- where things are connected and it was not immediately known.
It is exactly what I need! Thank you for your work! I also code in C++ where it is quite common to override built-in functions, I thought I can do the same thing in JS. Thank you!
– SphynxTech
Dec 30 '18 at 16:13
add a comment |
To repeat what's going on up in the comments; please, please, PLEASE, do not try and hack core functionality. If you would like to create a custom method to use in your code you can extend the Object
object...
Object.prototype.getEl = function( selector ){
return document.querySelector( `[special-attribute="${selector
}"]` );
}
console.log( document.getEl('potatoSalad') );
<div special-attribute="potatoSalad">one two three</div>
This way you can have the more condensed call document.getEl()
to target your desired elements while still preserving the original methods in JavaScript.
It may be possible to hack the core code; but it is very strongly recommended to not attempt this. As everyone discovers when they go down this path, it normally results in unexpected errors in the code -- where things are connected and it was not immediately known.
To repeat what's going on up in the comments; please, please, PLEASE, do not try and hack core functionality. If you would like to create a custom method to use in your code you can extend the Object
object...
Object.prototype.getEl = function( selector ){
return document.querySelector( `[special-attribute="${selector
}"]` );
}
console.log( document.getEl('potatoSalad') );
<div special-attribute="potatoSalad">one two three</div>
This way you can have the more condensed call document.getEl()
to target your desired elements while still preserving the original methods in JavaScript.
It may be possible to hack the core code; but it is very strongly recommended to not attempt this. As everyone discovers when they go down this path, it normally results in unexpected errors in the code -- where things are connected and it was not immediately known.
Object.prototype.getEl = function( selector ){
return document.querySelector( `[special-attribute="${selector
}"]` );
}
console.log( document.getEl('potatoSalad') );
<div special-attribute="potatoSalad">one two three</div>
Object.prototype.getEl = function( selector ){
return document.querySelector( `[special-attribute="${selector
}"]` );
}
console.log( document.getEl('potatoSalad') );
<div special-attribute="potatoSalad">one two three</div>
answered Dec 28 '18 at 18:12
DougDoug
9101714
9101714
It is exactly what I need! Thank you for your work! I also code in C++ where it is quite common to override built-in functions, I thought I can do the same thing in JS. Thank you!
– SphynxTech
Dec 30 '18 at 16:13
add a comment |
It is exactly what I need! Thank you for your work! I also code in C++ where it is quite common to override built-in functions, I thought I can do the same thing in JS. Thank you!
– SphynxTech
Dec 30 '18 at 16:13
It is exactly what I need! Thank you for your work! I also code in C++ where it is quite common to override built-in functions, I thought I can do the same thing in JS. Thank you!
– SphynxTech
Dec 30 '18 at 16:13
It is exactly what I need! Thank you for your work! I also code in C++ where it is quite common to override built-in functions, I thought I can do the same thing in JS. Thank you!
– SphynxTech
Dec 30 '18 at 16:13
add a comment |
This attribute cannot be found with a built-in method (or at least I
do not know it)
Yes there is a built-in method for finding special attributes and that method is called querySelector or if you want to retrieve more than one object, there is querySelectorAll that will return a list (called NodeList) of the document's elements that match the specified group of selectors.
Assuming you have a div with the attribute someWeirdAttribute
like this:
<div someWeirdAttribute="someWeirdValue">
Hello World
</div>
You can find the above element like this:
document.querySelector('[someWeirdAttribute="someWeirdValue"]');
Or if you want a more practical example, let us retrieve the attribute value as well as the div content from the above in this jsFiddle or in the code snippet below:
/* JavaScript */
var div = document.querySelector('[someWeirdAttribute="someWeirdValue"]');
var output = document.getElementById('info');
var btn = document.querySelector('button');
btn.addEventListener('click', function(){
var attrVal = div.getAttribute('someWeirdAttribute');
var divContent = div.textContent;
console.log(attrVal);
output.innerHTML = '';
output.innerHTML += `<p>The div atrribute value of <strong>someWeirdAttribute</strong> is <strong>${attrVal}</strong></p>
<p>The content inside the div is <strong>${divContent}</strong></p>`
})
<!-- HTML -->
<div someWeirdAttribute="someWeirdValue">
Hello World
</div>
<hr>
<button>
Get info about above element
</button>
<div id="info"></div>
1
A handy dandy thing I like to do with the defaultquerySelector
andquerySelectorAll
is to make shortcuts to them:var _ = document.querySelector.bind(document);
This makesdocument.querySelector(...)
become_(...)
.
– Marcus Parsons
Dec 28 '18 at 18:19
1
@MarcusParsons That is a really simple yet nice trick to use especially if there are a lot of variable assignments I have to make. It also makes the variable assignment section of my JS look cleaner. I honestly never thought of doing that before.Thanks for the tip man!! Will definitely start implementing this now.
– AndrewL
Dec 28 '18 at 18:22
1
Absolutely! I forgot to mentiondocument.querySelectorAll
as well. My assignment for that is usually:var __ = document.querySelectorAll.bind(document);
which of course makesdocument.querySelectorAll(...)
become__(...)
– Marcus Parsons
Dec 28 '18 at 18:25
add a comment |
This attribute cannot be found with a built-in method (or at least I
do not know it)
Yes there is a built-in method for finding special attributes and that method is called querySelector or if you want to retrieve more than one object, there is querySelectorAll that will return a list (called NodeList) of the document's elements that match the specified group of selectors.
Assuming you have a div with the attribute someWeirdAttribute
like this:
<div someWeirdAttribute="someWeirdValue">
Hello World
</div>
You can find the above element like this:
document.querySelector('[someWeirdAttribute="someWeirdValue"]');
Or if you want a more practical example, let us retrieve the attribute value as well as the div content from the above in this jsFiddle or in the code snippet below:
/* JavaScript */
var div = document.querySelector('[someWeirdAttribute="someWeirdValue"]');
var output = document.getElementById('info');
var btn = document.querySelector('button');
btn.addEventListener('click', function(){
var attrVal = div.getAttribute('someWeirdAttribute');
var divContent = div.textContent;
console.log(attrVal);
output.innerHTML = '';
output.innerHTML += `<p>The div atrribute value of <strong>someWeirdAttribute</strong> is <strong>${attrVal}</strong></p>
<p>The content inside the div is <strong>${divContent}</strong></p>`
})
<!-- HTML -->
<div someWeirdAttribute="someWeirdValue">
Hello World
</div>
<hr>
<button>
Get info about above element
</button>
<div id="info"></div>
1
A handy dandy thing I like to do with the defaultquerySelector
andquerySelectorAll
is to make shortcuts to them:var _ = document.querySelector.bind(document);
This makesdocument.querySelector(...)
become_(...)
.
– Marcus Parsons
Dec 28 '18 at 18:19
1
@MarcusParsons That is a really simple yet nice trick to use especially if there are a lot of variable assignments I have to make. It also makes the variable assignment section of my JS look cleaner. I honestly never thought of doing that before.Thanks for the tip man!! Will definitely start implementing this now.
– AndrewL
Dec 28 '18 at 18:22
1
Absolutely! I forgot to mentiondocument.querySelectorAll
as well. My assignment for that is usually:var __ = document.querySelectorAll.bind(document);
which of course makesdocument.querySelectorAll(...)
become__(...)
– Marcus Parsons
Dec 28 '18 at 18:25
add a comment |
This attribute cannot be found with a built-in method (or at least I
do not know it)
Yes there is a built-in method for finding special attributes and that method is called querySelector or if you want to retrieve more than one object, there is querySelectorAll that will return a list (called NodeList) of the document's elements that match the specified group of selectors.
Assuming you have a div with the attribute someWeirdAttribute
like this:
<div someWeirdAttribute="someWeirdValue">
Hello World
</div>
You can find the above element like this:
document.querySelector('[someWeirdAttribute="someWeirdValue"]');
Or if you want a more practical example, let us retrieve the attribute value as well as the div content from the above in this jsFiddle or in the code snippet below:
/* JavaScript */
var div = document.querySelector('[someWeirdAttribute="someWeirdValue"]');
var output = document.getElementById('info');
var btn = document.querySelector('button');
btn.addEventListener('click', function(){
var attrVal = div.getAttribute('someWeirdAttribute');
var divContent = div.textContent;
console.log(attrVal);
output.innerHTML = '';
output.innerHTML += `<p>The div atrribute value of <strong>someWeirdAttribute</strong> is <strong>${attrVal}</strong></p>
<p>The content inside the div is <strong>${divContent}</strong></p>`
})
<!-- HTML -->
<div someWeirdAttribute="someWeirdValue">
Hello World
</div>
<hr>
<button>
Get info about above element
</button>
<div id="info"></div>
This attribute cannot be found with a built-in method (or at least I
do not know it)
Yes there is a built-in method for finding special attributes and that method is called querySelector or if you want to retrieve more than one object, there is querySelectorAll that will return a list (called NodeList) of the document's elements that match the specified group of selectors.
Assuming you have a div with the attribute someWeirdAttribute
like this:
<div someWeirdAttribute="someWeirdValue">
Hello World
</div>
You can find the above element like this:
document.querySelector('[someWeirdAttribute="someWeirdValue"]');
Or if you want a more practical example, let us retrieve the attribute value as well as the div content from the above in this jsFiddle or in the code snippet below:
/* JavaScript */
var div = document.querySelector('[someWeirdAttribute="someWeirdValue"]');
var output = document.getElementById('info');
var btn = document.querySelector('button');
btn.addEventListener('click', function(){
var attrVal = div.getAttribute('someWeirdAttribute');
var divContent = div.textContent;
console.log(attrVal);
output.innerHTML = '';
output.innerHTML += `<p>The div atrribute value of <strong>someWeirdAttribute</strong> is <strong>${attrVal}</strong></p>
<p>The content inside the div is <strong>${divContent}</strong></p>`
})
<!-- HTML -->
<div someWeirdAttribute="someWeirdValue">
Hello World
</div>
<hr>
<button>
Get info about above element
</button>
<div id="info"></div>
/* JavaScript */
var div = document.querySelector('[someWeirdAttribute="someWeirdValue"]');
var output = document.getElementById('info');
var btn = document.querySelector('button');
btn.addEventListener('click', function(){
var attrVal = div.getAttribute('someWeirdAttribute');
var divContent = div.textContent;
console.log(attrVal);
output.innerHTML = '';
output.innerHTML += `<p>The div atrribute value of <strong>someWeirdAttribute</strong> is <strong>${attrVal}</strong></p>
<p>The content inside the div is <strong>${divContent}</strong></p>`
})
<!-- HTML -->
<div someWeirdAttribute="someWeirdValue">
Hello World
</div>
<hr>
<button>
Get info about above element
</button>
<div id="info"></div>
/* JavaScript */
var div = document.querySelector('[someWeirdAttribute="someWeirdValue"]');
var output = document.getElementById('info');
var btn = document.querySelector('button');
btn.addEventListener('click', function(){
var attrVal = div.getAttribute('someWeirdAttribute');
var divContent = div.textContent;
console.log(attrVal);
output.innerHTML = '';
output.innerHTML += `<p>The div atrribute value of <strong>someWeirdAttribute</strong> is <strong>${attrVal}</strong></p>
<p>The content inside the div is <strong>${divContent}</strong></p>`
})
<!-- HTML -->
<div someWeirdAttribute="someWeirdValue">
Hello World
</div>
<hr>
<button>
Get info about above element
</button>
<div id="info"></div>
edited Dec 28 '18 at 18:17
answered Dec 28 '18 at 18:12
AndrewLAndrewL
8,75741642
8,75741642
1
A handy dandy thing I like to do with the defaultquerySelector
andquerySelectorAll
is to make shortcuts to them:var _ = document.querySelector.bind(document);
This makesdocument.querySelector(...)
become_(...)
.
– Marcus Parsons
Dec 28 '18 at 18:19
1
@MarcusParsons That is a really simple yet nice trick to use especially if there are a lot of variable assignments I have to make. It also makes the variable assignment section of my JS look cleaner. I honestly never thought of doing that before.Thanks for the tip man!! Will definitely start implementing this now.
– AndrewL
Dec 28 '18 at 18:22
1
Absolutely! I forgot to mentiondocument.querySelectorAll
as well. My assignment for that is usually:var __ = document.querySelectorAll.bind(document);
which of course makesdocument.querySelectorAll(...)
become__(...)
– Marcus Parsons
Dec 28 '18 at 18:25
add a comment |
1
A handy dandy thing I like to do with the defaultquerySelector
andquerySelectorAll
is to make shortcuts to them:var _ = document.querySelector.bind(document);
This makesdocument.querySelector(...)
become_(...)
.
– Marcus Parsons
Dec 28 '18 at 18:19
1
@MarcusParsons That is a really simple yet nice trick to use especially if there are a lot of variable assignments I have to make. It also makes the variable assignment section of my JS look cleaner. I honestly never thought of doing that before.Thanks for the tip man!! Will definitely start implementing this now.
– AndrewL
Dec 28 '18 at 18:22
1
Absolutely! I forgot to mentiondocument.querySelectorAll
as well. My assignment for that is usually:var __ = document.querySelectorAll.bind(document);
which of course makesdocument.querySelectorAll(...)
become__(...)
– Marcus Parsons
Dec 28 '18 at 18:25
1
1
A handy dandy thing I like to do with the default
querySelector
and querySelectorAll
is to make shortcuts to them: var _ = document.querySelector.bind(document);
This makes document.querySelector(...)
become _(...)
.– Marcus Parsons
Dec 28 '18 at 18:19
A handy dandy thing I like to do with the default
querySelector
and querySelectorAll
is to make shortcuts to them: var _ = document.querySelector.bind(document);
This makes document.querySelector(...)
become _(...)
.– Marcus Parsons
Dec 28 '18 at 18:19
1
1
@MarcusParsons That is a really simple yet nice trick to use especially if there are a lot of variable assignments I have to make. It also makes the variable assignment section of my JS look cleaner. I honestly never thought of doing that before.Thanks for the tip man!! Will definitely start implementing this now.
– AndrewL
Dec 28 '18 at 18:22
@MarcusParsons That is a really simple yet nice trick to use especially if there are a lot of variable assignments I have to make. It also makes the variable assignment section of my JS look cleaner. I honestly never thought of doing that before.Thanks for the tip man!! Will definitely start implementing this now.
– AndrewL
Dec 28 '18 at 18:22
1
1
Absolutely! I forgot to mention
document.querySelectorAll
as well. My assignment for that is usually: var __ = document.querySelectorAll.bind(document);
which of course makes document.querySelectorAll(...)
become __(...)
– Marcus Parsons
Dec 28 '18 at 18:25
Absolutely! I forgot to mention
document.querySelectorAll
as well. My assignment for that is usually: var __ = document.querySelectorAll.bind(document);
which of course makes document.querySelectorAll(...)
become __(...)
– Marcus Parsons
Dec 28 '18 at 18:25
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53962381%2foverride-html-dom-element-methods-js%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Just out of curiousity, why would you want to build a custom method for something that is already there as a built-in function?.
– AndrewL
Dec 28 '18 at 17:48
Just wondering, why do you need to do your own method, would
document.querySelectors
not work for you?– Pytth
Dec 28 '18 at 17:49
@AndrewL, My library uses a special attribute to locates divs. This attribute cannot be found with a built-in method (or at least I do not know it). I need to create a built-in method to make easily the interaction user-library.
– SphynxTech
Dec 28 '18 at 17:50
document.querySelector('[whateverAttributeYouHave]')
will find any element with whatever attribute– Taplar
Dec 28 '18 at 17:52
2
document.querySelector('div[special-attribute="potatoSalad"]')
querySelector( as mentioned by @Pytth ) should let you query by special attributes of your divs. It's always dicey to hack core functionality.– Doug
Dec 28 '18 at 17:52