0

I'm making a shorthand function for a build in JavaScript function:

function editById(getId) {
  document.getElementById(getId);
}

then I tried using it in my script.js:

function run() {
  document.editById("test").style.color="blue";
}

then my HTML:

<p id="test">TestTestestestse</p>
<input type="button" onclick="run()" value="Change text color">

This doesn't work with editById, but it does getElementById...

ABOVE SOLVED


Adding onto that:

Now this doesn't work:

shortHand.js

// Long term document functions
document.editById = function (find) { return document.getElementById(find); }
document.editByClass = function (find2) { return document.getElementsByClassName(find2); }
document.editByTag = function (find3) { return document.getElementsByTagName(find3); }

script.js

function run() {
  document.editById("test").style.color="blue";
}
function run2() {
  document.editByClass("test").style.color="blue";
}
function run3() {
  document.editByTag("h1").style.color="blue";
}

HTML

<p id="test">TestTestestestse</p>
<p class="test">TestTestestestse222</p>
<h1>TestTestestestse368585475</h1>
<input type="button" onclick="run()" value="Change text color">
<input type="button" onclick="run2()" value="Change text color">
<input type="button" onclick="run3()" value="Change text color">
1
  • Where did you define document.editById? Commented Jan 3, 2014 at 8:16

2 Answers 2

5

Modify your function as

function editById(getId) {
  //return object
  return document.getElementById(getId);
}

function run() {
  editById("test").style.color="blue";
}

DEMO

Additionally, You also use like

document.editById = function (getId) {
  return document.getElementById(getId);
}

function run() {
  document.editById("test").style.color = "blue";
}

DEMO

Sign up to request clarification or add additional context in comments.

4 Comments

Ha, should have known. Thank you so much.
Or if you want to be fancy, var editById = document.getElementById.bind(document);
@Xero, document.getElementsByTagName with return you a HTMLCollection of elements with the given tag name. and document.getElementsByClassName will return a set of elements which have all the given class names. So you have to use like document.editByClass("test")[0]
I will, it wasn't letting me a sec ago. Thanks again!
-1

the function editById is registered on document Object but on window. you can not call the function like this

you may call the function like this

function run() {
  editById("test").style.color="blue";
}

1 Comment

I tried this, but it didn't work. @Satpal fixed it my adding the return

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.