jQuery select element by XPath - javascript

I have an XPath selector. How can I get the elements matching that selector using jQuery?
I've seen https://developer.mozilla.org/en/Introduction_to_using_XPath_in_JavaScript but it doesn't use jQuery, and it seems a little too verbose, and I suppose it's not cross-browser.
Also, this http://jsfiddle.net/CJRmk/ doesn't seem to work.
alert($("//a").length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>

If you are debugging or similar - In chrome developer tools, you can simply use
$x('/html/.//div[#id="text"]')

document.evaluate() (DOM Level 3 XPath) is supported in Firefox, Chrome, Safari and Opera - the only major browser missing is MSIE. Nevertheless, jQuery supports basic XPath expressions: http://docs.jquery.com/DOM/Traversing/Selectors#XPath_Selectors (moved into a plugin in the current jQuery version, see https://plugins.jquery.com/xpath/). It simply converts XPath expressions into equivalent CSS selectors however.

First create an xpath selector function.
function _x(STR_XPATH) {
var xresult = document.evaluate(STR_XPATH, document, null, XPathResult.ANY_TYPE, null);
var xnodes = [];
var xres;
while (xres = xresult.iterateNext()) {
xnodes.push(xres);
}
return xnodes;
}
To use the xpath selector with jquery, you can do like this:
$(_x('/html/.//div[#id="text"]')).attr('id', 'modified-text');
Hope this can help.

Related

ie javascript remove element

I'm using this code to remove an element
function deleteMyElement(id) {
var elem = document.getElementById("myElement" + id);
elem.remove();
}
It works fine for chrome and firefox but not for ie. The console shows me an error: The object does not support the remove method.
How can I get this working in all common browsers?
By doing it the normal way.
elem.parentNode.removeChild(elem);
.remove is a jQuery method, not JavaScript.
EDIT: Apparently, it's planned to be a JavaScript method. Kind of daft in my opinion, but there you go. Since it's experimental, it is not necessarily supported in all browsers.

jQuery getelementsbyclassname equivalent

I have written a lot of JavaScript code using getElementsByClass name and now realised this is not supported in IE8 so am trying to swap them all for the jQuery equivalent.
My code runs without errors using
div1.getElementsByClassName("div2");
however if I swap this line for
$(".div1 .div2");
my code produces an error "Uncaught NotFoundError: An attempt was made to reference a Node in a context where it does not exist."
What is the difference between the JavaScript code and jQuery code that could make the code behave differently?
If you've already written code using getElementsByClassName, you might be better off using a shim or polyfill so you don't have to rewrite existing code.
Unfortunately, most of the stuff out there only supplies document.getElementsByClassName, so if you're using it from other elements, you'll have to roll your own you can try this one I wrote a while back.
// getElementsByClassName polyfill
(function(){
if (document.getElementsByClassName)
return;
if (!window.Element)
throw "Can't polyfill getElementsByClassName";
function gEBCN(className) {
var all = this.getElementsByTagName("*"),
rex = new RegExp("(?:\\s|^)" + className + "(?:\\s|$)"),
out = [],
element, i;
for (i = all.length; i--;) {
element = all[i];
if (element.className.match(rex))
out.unshift(element);
}
return out;
}
var el = window.Element.prototype;
var doc = document.constructor.prototype;
el.getElementsByClassName = doc.getElementsByClassName = gEBCN;
}());
This script checks if document.getElementsByClassName exists, and if it doesn't, it creates document.getElementsByClassName and Element.prototype.getElementsByClassName with equivalent functionality. Since all HTML elements have Element.prototype in their prototype chain, you'll be able to call .getElementsByClassName on any element, just as you can in any browser that has native support for the function. In other words, you can just drop this code at the top of your file or put it a separate file and include it, and then your current scripts should work in old IE and any other browsers that don't support .getElementsByClassName.
Note that jQuery 2.x does not support IE6/7/8. This might be the problem. Instead, use the 1.x branch (for example version [1.10.2]), which still supports those browsers.
When using a 1.x version of jQuery, the following should be the correct selector for what you want.
$(".div1 .div2") //or:
$(".div1").find(".div2") // or, if .div2 is a direct descendant:
$(".div1 > .div2")

Javascript with Firefox innerText issue [duplicate]

This question already has answers here:
'innerText' works in IE, but not in Firefox
(15 answers)
Closed 7 years ago.
function OpenWindow(anchor) {
var toUsername = anchor.innerText;
window.open("ChatWindow.aspx?username=" + toUsername,'_blank', "width=340,height=200");
}
this function opens up a page with parameter as undefined in firefox where as in google chrome I get proper value.
Firefox url:
http://localhost:9452/ChatWindow.aspx?username=undefined
What is the solution for this issue?
While innerText is non-standard, it significantly differs from textContent, because first one is doing pretty printing (for example, <br/> are converted to new lines), while second one - is not.
So, while common wisdom is to use:
var toUsername = anchor.innerText || anchor.textContent;
or some kind of wrapper, it can probably be smarter to just use jQuery's .text or its analog from other library you are using.
try to change anchor.innerText with:
anchor.textContent
this hopefully works in all browsers.
also see here: 'innerText' works in IE, but not in Firefox
P.S. I really reccomend using JQuery to avoid these kind of issues and to be sure to always write fully cross-browser javascript.
innerText is a Microsoft invention whereas textContent is a W3C standard.
function OpenWindow(anchor) {
var toUsername = anchor.textContent || anchor.innerText || '';
window.open("ChatWindow.aspx?username=" + toUsername,'_blank', "width=340,height=200");
}
This should work. MooTools or some other JavaScript framework should be able to help with cross-browser inconsistencies.
use textContent for innerText.
example
<script>
function change()
{
document.getElementById("label").textContent="Hello";
}
</script>
it will work on ff. and chrome too. but not work on IE.
I was getting the same problem because Firefox does not support the innerText property, instead, it supports the textContent property. so check for the browser’s feature support to use the correct property accordingly.
if(document.all){
document.getElementById('element').innerText = "myText";
} else{
document.getElementById('element').textContent = "myText";
}
or it's better to use Jquery to resolve cross browser issues.
Usage:
$('element').text("myText");

Replacement of .all() function for Browsers other than IE

I am using following code
myEl = document.createElement("myElement") ;
//in a loop
myEl.innerHTML = myEl.innerHTML + currElement.outerHTML ; //some elements getting added to it
var newElement = myEl.all(idToSearch) ;
the last line is not working for browsers other than IE..
I am particularly using Chrome, is there any alternative for it???
You can use querySelector() on elements that aren't yet attached to the document:
var newElement = myEl.querySelector("#" + idToSearch);
all is a proprietary IE extension totally unsupported by standards compliant browsers.
Use document.getElementById() or start looking at libraries like jquery (which would also help with the innerHTML problems you're likely to encounter).

JavaScript: iterating over document.evaluate() XPathResult returns null

I am trying to get all objects but it doesn't work.
var tmp = document.evaluate("//tr", document, null, XPathResult.ANY_TYPE, null);
tmp.iterateNext returns me null;
If you are working in IE, then you should know that document.evaluate does not exist there (see this similar question and the last couple of paragraphs here).
Why not just document.getElementsByTagName("tr");?
In my opinion, using an existing JS libraries such as JQuery is usually more reliable in cases like this.
document.getElementsByTagName("tr");
It also will not work, because IE some versions doesn't support this method for elements, which has not such attribute like 'name'.

Categories

Resources