Reputation: 6168
I am using javascript on client-side in my app, I need to get the element based on the id, class and tagname, I am using following code for getting element using id
.
HTML:
<!Doctype>
<html>
<head>
<script>
(function (tag,fp,n) {
var d = document;
a = d.createElement(tag), m = d.getElementsByTagName(tag)[0];
a.async = 1;
a.src = fp;
m.parentNode.insertBefore(a, m)
})('script', 'cs.js', 'cs');
</script>
</head>
<body>
<div id="id">click me</div>
</body>
</html>
javascript(cs.js):
;(function(w, d) {
var util = {
getElements : function(selector) {
var result = [];
var hashIndex = selector.indexOf("#");
var dotIndex = selector.indexOf(".");
if(hashIndex > -1){
selector = selector.substring(hashIndex+1);
var domElem = d.getElementById(selector);
console.log(domElem);
if(domElem !=null){
result.push(domElem);
}
}
else if(dotIndex > -1){
selector = selector.substring(dotIndex+1);
var domElem = d.getElementsByClassName(selector);
if(domElem !=null){
result = domElem;
}
}else{
var domElem = d.getElementsByTagName(selector);
if(domElem !=null){
result = domElem;
}
}
return result;
}
};
console.log(util.getElements("#id"));
})(window, document);
It works correctly in chrome, firefox but in opera it gives null
.
Browser Info:
Opera/9.80 (X11; Linux x86_64) Presto/2.12.388 Version/12.15
Any workaround for this issue?
Upvotes: 1
Views: 910
Reputation: 943537
Your <script>
element appears before the <div>
element you are trying to select.
Using async
doesn't guarantee that the DOM Ready event will fire before the script runs.
Move the script so it appears later in the document, or bind it to an event handler.
Upvotes: 3
Reputation: 23472
I don't have that version of Opera to test your claim but you could consider document.querySelector as an alternative.
HTML
<div id="id"></div>
Javascript
var domElement = document.querySelector("#id");
console.log(domElement);
On jsfiddle
Update for @bergi
Here is an example where the environment has been broken, this may be intentional in design (who knows), anyway the OP has not control over said environment.
document.getElementById = function () {
return null;
};
var domElement = document.getElementById("id");
console.log(domElement);
domElement = document.querySelector("#id");
console.log(domElement);
On jsfiddle
Oh dear, getElementById
does not work, but querySelector
does.
I am not disagreeing that the question is vague, but still ...
Upvotes: 0
Reputation: 1712
Maybe you could try giving the domElement a name via "name"-attribute and do:
var domElement = document.getElementsByName("element_name")[0];
console.log(domElement);
I hope it works that way.
Upvotes: 0