How to generate unique css selector for DOM element? - javascript

I need to generate unique css selector for elements.
Particularly, I have onclick event handler that should remember what target element
was clicked and send this info to my server. Is there a way to do it without doing DOM modifications?
P.S. my javascript code supposed to be run on different
3-rd party websites so I can't make any assumptions about html.

This function creates a long, but quite practical unique selector, works quickly.
const getCssSelector = (el) => {
let path = [], parent;
while (parent = el.parentNode) {
path.unshift(`${el.tagName}:nth-child(${[].indexOf.call(parent.children, el)+1})`);
el = parent;
}
return `${path.join(' > ')}`.toLowerCase();
};
Example result:
html:nth-child(1) > body:nth-child(2) > div:nth-child(1) > div:nth-child(1) > main:nth-child(3) > div:nth-child(2) > p:nth-child(2)
The following code creates a slightly more beautiful and short selector
const getCssSelectorShort = (el) => {
let path = [], parent;
while (parent = el.parentNode) {
let tag = el.tagName, siblings;
path.unshift(
el.id ? `#${el.id}` : (
siblings = parent.children,
[].filter.call(siblings, sibling => sibling.tagName === tag).length === 1 ? tag :
`${tag}:nth-child(${1+[].indexOf.call(siblings, el)})`
)
);
el = parent;
};
return `${path.join(' > ')}`.toLowerCase();
};
Example result:
html > body > div > div > main > div:nth-child(2) > p:nth-child(2)

Check this CSS selector generator library #medv/finder
Generates shortest selectors
Unique selectors per page
Stable and robust selectors
2.9 kB gzip and minify size
Example of generated selector:
.blog > article:nth-child(3) .add-comment

Yes, you could do this. But with a few caveats. In order to be able to guarantee that selectors are unique, you'd need to use :nth-child() which isn't universally supported. If you're then wanting to put these CSS selectors into CSS files, it won't work in all browsers.
I'd do it with something like this:
function () {
if (this.id) {
return sendToServer('#' + this.id);
}
var parent = this.parentNode;
var selector = '>' + this.nodeName + ':nth-child(' + getChildNumber(this) ')';
while (!parent.id && parent.nodeName.toLowerCase() !== 'body') {
selector = '>' + this.nodeName + ':nth-child(' + getChildNumber(parent) + ')' + selector;
parent = parent.parentNode;
}
if (parent.nodeName === 'body') {
selector = 'body' + selector;
} else {
selector = '#' + parent.id + selector;
}
return sendToServer(selector);
}
Then add that to your click handler for each element you want to model. I'll leave you to implement getChildNumber().
Edit: Just seen your comment about it being 3rd party code... so you could add an event argument, replace all instances of this with event.target and then just attach the function to window's click event if that's easier.

let say you have a list of links for the sake of simplicity: you can simply pass the index of the triggering element in the collection of all elements
...
...
...
the js (jQuery 1.7+, I used .on()otherwise use bind()) function can be
var triggers = $('a');
triggers.on('click', function(e) {
e.preventDefault();
var index = triggers.index($(this));
/* ajax call passing index value */
});
so that if you click on third element index value passed will be 2. (0-based index);
of course this is valid as long as the code (the DOM) doesn't change. Later you can use that index to create a css rule to that element e.g. using :nth-child
Otherwise if each one of your elements have a different attribute (like an id) you can pass that attribute
example on JsFiddle : http://jsfiddle.net/t7J8T/

You could probably traverse the DOM tree from the node back to the body element to generate a selector.
Firebug has a feature for this, both using XPath and CSS selectors.
See this answer

"use strict";
function getSelector(_context){
var index, localName,pathSelector, that = _context, node;
if(that =='null') throw 'not an dom reference';
index = getIndex(that);
while(that.tagName){
pathSelector = that.localName+(pathSelector?'>'+pathSelector :'');
that = that.parentNode;
}
pathSelector = pathSelector+':nth-of-type('+index+')';
return pathSelector;
}
function getIndex(node){
var i=1;
var tagName = node.tagName;
while(node.previousSibling){
node = node.previousSibling;
if(node.nodeType === 1 && (tagName.toLowerCase() == node.tagName.toLowerCase())){
i++;
}
}
return i;
}
document.addEventListener('DOMContentLoaded', function(){
document.body.addEventListener('mouseover', function(e){
var c = getSelector(e.target);
var element = document.querySelector(c);
//console.log(element);
console.log(c);
//element.style.color = "red"
});
});
you can try this one. without using jquery.

The Firefox developer console uses the following heuristics to find a unique selector for an element. The algorithm returns the first suitable selector found. (Source)
If the element has a unique id attribute, return the id selector #<idname>.
If the tag is html, head, or body, return the type selector <elementname>.
For each class of the element:
If the class is unique to the element, return the class selector .<classname>.
If the tag/class combination is unique, return the selector <elementname>.<classname>.
Compute the element's index in its parent's child list. If the selector <elementname>.<classname>:nth-child(<index>) is unique, return that.
Let index be the element's index in its parent's child list.
If the parent node is the root node, return the selector <elementname>:nth-child(<index>).
Otherwise, recursively find a unique selector for the parent node and return <parentselector> > <elementname>:nth-child(<index>).

Related

jQuery closest (inside and outside DOM tree )

Given an element and any selector, I need to find the closest element which matches it, not matter if it's inside the element or outside of it.
Currently jQuery doesn't provide such traversing functionality, but there is a need. Here is the scenario:
A list of many items where the <button> element reside inside <a>
<ul>
<li>
<a>
<button>click me</button>
<img src="..." />
</a>
</li>
<li>
<a>
<button>click me</button>
<img src="..." />
</a>
</li>
...
</ul>
Or the <button> element might reside outside of the <a> element
<ul>
<li>
<a>
<img src="..." />
</a>
<button>click me</button>
</li>
<li>
<a>
<img src="..." />
</a>
<button>click me</button>
</li>
...
</ul>
The very very basic code would look like this:
$('a').closest1('button'); // where `closest1` is a new custom function
// or
$('a').select('> button') // where `select` can parse any selector relative to the object, so it would also know this:
$('a').select('~ button') // where the button is a sibling to the element
the known element is <a> and anything else can change. I want to locate the nearest <button> element for a given <a> element, no matter if that button is inside or outside of <a>'s DOM tree.
It would be very logical that native jQuery function "closest" would do as the name suggests and find the closest, but it only searches upwards as you all know. (it should have been named differently IMO).
Does anyone know any custom traversing function which does the above?
Thanks. (i'm asking you people because someone must have written this for sure but I was unlucky to find a lead on the internet)
Here is another attempt using the idea I mentioned in comment:
$(this).parents(':has(button):first').find('button').css({
"border": '3px solid red'
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/z3vwk1ko/40/
It basically looks for the first ancestor that contains both the elements (clicked and target), then finds the target.
Performance:
With regard to speed, this is used at human interaction speeds, i.e. a few times per second maximum, so being a "slow selector" is irrelevant if it solves the problem, in a reasonably obvious way, with minimal code. You would have to click 100s of times per second to notice any different compared to a fast selector :)
None of the built-in selectors allow searching up and down the tree. I did create a custom findThis extension that allows you to do things like $elementClicked.('li:has(this) button') which would allow you to do something similar.
// Add findThis method to jQuery (with a custom :this check)
jQuery.fn.findThis = function (selector) {
// If we have a :this selector
if (selector.indexOf(':this') > 0) {
var ret = $();
for (var i = 0; i < this.length; i++) {
var el = this[i];
var id = el.id;
// If not id already, put in a temp (unique) id
el.id = 'id' + new Date().getTime();
var selector2 = selector.replace(':this', '#' + el.id);
ret = ret.add(jQuery(selector2, document));
// restore any original id
el.id = id;
}
ret.selector = selector;
return ret;
}
// do a normal find instead
return this.find(selector);
}
// Test case
$(function () {
$('a').click(function () {
$(this).findThis('li:has(:this) button').css({
"border": '3px solid red'
});
});
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/z3vwk1ko/38/
note: Click the images/links to test.
A while ago I wanted to do the same for a completely DOM-based text editor, and needed to find the previous (ARR LEFT) and next (ARR RIGHT) text nodes, both up and down the tree. Based on this code I have made an adaptation suiting this question. Be warned, it's quite performance-heavy, but it is adapted to any scenario. There are two functions findPrevElementNode and findNextElementNode which both return an object with properties:
match - returns the closest matching node for the search or FALSE if none is found
iterations - returns the number of iterations done to find the node. This allows you to check whether the previous node is closer than the next or vice-versa.
The parameters are as follows:
//#param {HTMLElement} referenceNode - The node from which to start the search
//#param {function} truthTest - A function that returns true for the given element
//#param {HTMLElement} [limitNode=document.body] - The limit up to which to search to
var domUtils = {
findPrevElementNode: function(referenceNode, truthTest, limitNode) {
var element = 1,
iterations = 0,
limit = limitNode || document.body,
node = referenceNode;
while (!truthTest(node) && node !== limit) {
if (node.previousSibling) {
node = node.previousSibling;
iterations++;
if (node.lastChild) {
while (node.lastChild) {
node = node.lastChild;
iterations++;
}
}
} else {
if (node.parentNode) {
node = node.parentNode;
iterations++;
} else {
return false;
}
}
}
return {match: node === limit ? false : node, iterations: iterations};
},
findNextElementNode: function(referenceNode, truthTest, limitNode) {
var element = 1,
iterations = 0,
limit = limitNode || document.body,
node = referenceNode;
while (!truthTest(node) && node !== limit) {
if (node.nextSibling) {
node = node.nextSibling;
iterations++;
if (node.firstChild) {
while (node.firstChild) {
node = node.firstChild;
iterations++;
}
}
} else {
if (node.parentNode) {
node = node.parentNode;
iterations++;
} else {
return false;
}
}
}
return {match: node === limit ? false : node, iterations: iterations};
}
};
In your case, you could do:
var a = domUtils.findNextElementNode(
document.getElementsByTagName('a')[0], // known element
function(node) { return (node.nodeName === 'BUTTON'); }
);
var b = domUtils.findPrevElementNode(
document.getElementsByTagName('a')[0], // known element
function(node) { return (node.nodeName === 'BUTTON'); }
);
var result = a.match ? (b.match ? (a.iterations < b.iterations ? a.match :
(a.iterations === b.iterations ? fnToHandleEqualDistance() : b.match)) : a.match) :
(b.match ? b.match : false);
See it in action.
DEMO PAGE / GIST
I have solved working by logic, so I would first look inside the elements, then their siblings, and last, if there are still unfound items, I would do a recursive search on the parents.
JS CODE:
jQuery.fn.findClosest = function (selector) {
// If we have a :this selector
var output = $(),
down = this.find(selector),
siblings,
recSearch,
foundCount = 0;
if(down.length) {
output = output.add(down);
foundCount += down.length;
}
// if all elements were found, return at this point
if( foundCount == this.length )
return output;
siblings = this.siblings(selector);
if( siblings.length) {
output = output.add(siblings);
foundCount += siblings.length;
}
// this is the expensive search path if there are still unfound elements
if(foundCount < this.length){
recSearch = rec(this.parent().parent());
if( recSearch )
output = output.add(recSearch);
}
function rec(elm){
var result = elm.find(selector);
if( result.length )
return result;
else
rec(elm.parent());
}
return output;
};
// Test case
var buttons = $('a').findClosest('button');
console.log(buttons);
buttons.click(function(){
this.style.outline = "1px solid red";
})
I think using sibling selector (~) or child selector (>) will solve your purpose(What ever your case is!!).

JavaScript get h1 elements in HTML document and update unique IDs

I have a legacy html document containing h1 elements which don't have ids.
What I would like to achieve is to be able, using JavaScript, to get all h1(s) and then add to each a unique ID.
I have searched but could not find a solution that works.
Try getting all of them with document.getElementsByTagName("h1"). Loop through them, check if they have an id, and work appropriately. Try:
var h1s = document.getElementsByTagName("h1");
for (var i = 0; i < h1s.length; i++) {
var h1 = h1s[i];
if (!h1.id) {
h1.id = "h1" + i + (new Date().getTime());
}
}
DEMO: http://jsfiddle.net/kTvA2/
After running the demo, if you inspect the DOM, you'll see 3 out of the 4 h1 elements have a new, unique id. The one with the id in the first place isn't changed.
Note that this code needs to run after all elements are ready/rendered, which can be achieved by putting the code inside of a window.onload handler. The demo provided is set up to implicitly run the code then.
UPDATE:
With jQuery, you could use:
$(document).ready(function () {
$("h1:not([id])").attr("id", function (i, attr) {
return "h1" + i + (new Date().getTime());
});
});
DEMO: http://jsfiddle.net/kTvA2/7/
Use querySelectorAll() to get all of your header elements, then iterate over the result and generate yor unique id for each element.
var headerElements = document.querySelectorAll('h1');
for(h in headerElements) {
if(headerElements[h] instanceof Element) {
headerElements[h].id=uniqueIDgenerator();
}
}

How to add a child selector and child element to a variable, referencing an element

I need to add a child selector and child element to a variable, referencing an element.
but i can't seem to get it working..
I've tried;
var wrapper = $('#wrapper');
if($(wrapper+' > .box').length > 0)) // unsuccessful
if(wrapper.add(' > .box').length > 0)) // unsuccessful
and
if(wrapper[0]+' > .box'.length > 0)) // unsuccessful
thanks cam
The issue is that you're confusing the selection with the selector. If you were to have done:
var selector = "#wrapper";
var wrapper = $(selector);
Then you could test it appropriately:
if ( $(selector + " > .box").length )
Note that > is the first-child selector.
I'm guessing .box is a direct child of wrapper, and you're trying to check if it exists, so you could probably do:
var wrapper = $('#wrapper');
if ( wrapper.children('.box').length ) {
//wrapper has direct child .box
}

jQuery selector for an element that directly contains text?

I was able to get this partially working using the :contains selector, but my problem is if an element contains an element that contains the text it is still returned. For example:
$('div:contains("test")')
Will select both divs below:
<div>something else
<div>test</div>
</div>
fiddle: http://jsfiddle.net/TT7dR/
How can I select only divs that "directly" contain the text? Meaning that in the above example only the child div would be selected.
UPDATE:
Just to clarify, if I were searching for the text "something else" instead of "test" then I would like to only find the parent div.
$('div>:contains("test")') is not a general solution, it only works for your specific example. It still matches any element whose descendants contain the text test, as long as its parent is a div.
There is in fact currently no selector that will select only direct parents of text nodes containing your target text. To do it you would have to walk the DOM tree yourself checking each text node you find for the target text, or write a plugin to do the same. It'd be slow, but then not as slow as :contains already is (it's not a standard CSS selector so you don't get browser-native fast selector support).
Here's a plain DOM function you could use as a starting point. It might be improved to find text in adjacent (non-normalised) text nodes, or to hide it in a plugin/selector-extension.
function findElementsDirectlyContainingText(ancestor, text) {
var elements= [];
walk(ancestor);
return elements;
function walk(element) {
var n= element.childNodes.length;
for (var i= 0; i<n; i++) {
var child= element.childNodes[i];
if (child.nodeType===3 && child.data.indexOf(text)!==-1) {
elements.push(element);
break;
}
}
for (var i= 0; i<n; i++) {
var child= element.childNodes[i];
if (child.nodeType===1)
walk(child);
}
}
}
Just to complete the knowledge base. If you need to get all DOM elements within the body (not only DIVs) that contain specific text or characters you can use:
function getNodesThatContain(text) {
var textNodes = $(document).find(":not(iframe, script)")
.contents().filter(
function() {
return this.nodeType == 3
&& this.textContent.indexOf(text) > -1;
});
return textNodes.parent();
};
console.log(getNodesThatContain("test"));
Hope that helps.
jsfiddle: http://jsfiddle.net/85qEh/2/
Credits: DMoses
You might have to do an in-efficient query. Do not use this solution if someone finds a selector that manages to filter out child elements: http://viralpatel.net/blogs/2011/02/jquery-get-text-element-without-child-element.html
$("div:contains('test')")
.clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.filter(":contains('test')")
edit: that snippet above is just to test the element, in implementation it would look more like this: http://jsfiddle.net/rkw79/TT7dR/6/
$("div:contains('test')").filter(function() {
return (
$(this).clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.filter(":contains('test')").length > 0)
}).css('border', 'solid 1px black');
try adding the greater than:
$('div>:contains("test")')
Finds specific element, but not parents
var elementsContainingText = ($(':contains("' + text + '")', target)).filter(function() {
return $(this).contents().filter(function() {return this.nodeType === 3 && this.nodeValue.indexOf(text) !== -1; }).length > 0;
});
This seems to work for me:
$('div >:contains("test")');
http://jsfiddle.net/TT7dR/1/
This forces the matched :contains selector to be a direct child of the <div> element
Try the following:
$("div>div:contains(test):only-of-type")
Add more alternative:
if($(selector).text().trim().length) {
var thetext = $(selector).contents().filter(function(){
return this.nodeType === 3;
}).text().trim();
console.log(thetext);
}
It will select the text only and remove any element with tag!
Reference
You can simply select the element that doesn't have your element
$('div:contains("test"):not(:has(> div))')
less code to write (but with a little limitation):
let selector = $('div:contains("test")');
selector.not(selector.has('div:contains("test")'))
Just use the jQuery function (.has) because the css :has is experimental:
https://developer.mozilla.org/en-US/docs/Web/CSS/:has#Browser_compatibility
Limitation:
When you have a structure like this:
<div>
<div>test</div>
test
</div>
Then only the inner div - Element will be found by this solution. This is because there is still an Element - Child of the div that :contains the string "test".

Best way to GET the xpath and css selector of a specific element

Looking for the best way to GET the xpath and css selector of a specific element using jQuery or Extjs. To basically select a random element and traverse up the dom and retreive it's unique css selector or xpath. Is there a function that can do this already or does anyone have a custom function that can do this?
Why not just check for an "id" value, and if there is one there just use it. If there isn't one, generate a unique random "id" value, give it to the element, and then use that.
edit: here's a proof-of-concept jQuery hack to build up a selector for any element you click on.
$('*').unbind('click.m5').bind('click.m5', function(ev) {
if (this != ev.target) return;
var cn = function(elem) {
var n = $(elem).parent().children().index(elem);
return elem.tagName + ':nth-child(' + n + ')';
};
var selector = cn(this);
$(this).parents().each(function() {
if (/BODY|HTML/.test(this.tagName))
selector = this.tagName + '>' + selector;
else
selector = cn(this) + '>' + selector;
});
console.log("Selector: " + selector);
$(selector).css('background-color', 'red');
});
There are an infinite number of selectors for any given element. What do you need it for? You might be able to use Firefox plugin like XPather?

Categories

Resources