I need to be able to get an unqiue selector for each element on a page.
For example, when I click on an element I want to do something like this:
$(document).click(function(){
var sel = getUniqueSel(this);
});
So, after storing the sel value in a DB I can get that value and simply access the element by
var el = $(sel);
I can't change and don't know anything about the HTML structure of the page and I can't simply add unique ID's (using JS) to every element as this would be inefficient.
Another approach might be to wander up the dom tree and create a path to the element, which you can save and use it later as a selector again, although that might not be bulletproof, but maybe its a point where you can start off.
Edit: Updated the Answer with your suggestion in the comment, now it returns the id if available
Just visit the example on JSBin And click the document twice.
but notice what gets highlighted..
jQuery.fn.getPath = function () {
if (this.length != 1) throw 'Requires one element.';
var path, node = this;
if (node[0].id) return "#" + node[0].id;
while (node.length) {
var realNode = node[0],
name = realNode.localName;
if (!name) break;
name = name.toLowerCase();
var parent = node.parent();
var siblings = parent.children(name);
if (siblings.length > 1) {
name += ':eq(' + siblings.index(realNode) + ')';
}
path = name + (path ? '>' + path : '');
node = parent;
}
return path;
};
var sel;
$(document)
.click(function (e, a) {
if (!sel) {
sel = $("#comment-21702402")
.getPath();
alert("Path is: " + sel + ", hiding the Element -> Click again to highlight");
} else {
$(sel)
.css("background-color", "yellow");
}
});
One way to do this is to get all the information you can get on the element that was clicked.
So when you save it to the database you can save it as a text for example:
If the element you clicked on is: <div> I'm a div </div>
$(document).click(function(){
var tagName = $(this).prev().prop('tagName');
var attributes = {};
if( this.length ) {
$.each( this[0].attributes, function( index, attr ) {
attributes[ attr.name ] = attr.value;
} );
}
var elText=$(this).html();
saveToDB(tagName,attributes,elText);
});
You can later find the element using the attributes you have or simply use
$(tagName+'['+attribute+'="'+value+'"]:contains("'+elText+'")')
I think this should help
Related
I have this JQuery function:
var objects = document.querySelectorAll('object');
// Iterate through objects
$('object').each( function() {
var link = $(this).attr('data');
$(this).append('click here');
});
It goes through all <object> items in a page and appends a link to the end of them (all of the objects in this case are used to create an embed document.) However, I want to edit the function so that it also edits an attribute in the object tag, preferably changing the name attribute, and also add an if statement to check to see if the object tag contains this new name.
You can use .attr() to get/set the name attribute, also you can use .is() along with attribute selector
// Iterate through objects
var $objects = $('object');
$objects.each(function() {
var $this = $(this);
$this.append('<a href="' + $this.attr('data')
'">click here</a>');
var nametoset = ''; //some logic to find the name
if ($objects.is('[name="' + nametoset + '"]')) {
//name already exists so do something
} else {
$this.attr('name', nametoset);
}
});
$('object').each( function() {
var link = $(this).attr('data');
var newlink = $('click here');
newLink.attr("name","jonny");
$(this).append(newLink);
});
OR
$('object').each( function() {
var link = $(this).attr('data');
var newname = "jonny";
var newlink =$ ('click here');
$(this).append(newLink);
});
I want to pull into an array the classes of all of the <img> in a particular <div> and then use those classes to delete the first <img> that shares that class in a different <div>.
So far, I have this that calls the original array:
var class = $('.frame div img').each(function() {
return $(this).class;
}).get();
class.forEach(function(entry) {
console.log(entry);
});
The log outputs a list of the <img></img> lines.
After that, I get stuck.
//Iterate through array and delete first <img> in #grid that has the same class, limit one per iteration.
// var img_class = $.each(class, function(key, value) {
// console.log(value);
// return $(this).attr('class');
// });
$('#grid img').each(function(){
if($(this).attr('class') == img_class){
$(this).remove();
}
});
The goals are:
Getting an array of classes into the img_class variable
Delete only the first <img> as it iterates through each class in the array
Thanks!
I am not sure if I understood it right but would something like this be of any help?
var firstIDs = "";
$('.frame div img').each(function() {
firstIDs += $(this).attr('id') + ",";
});
var SplitIDs = firstIDs.split(",");
$('#grid img').each(function(){
for(var i = 0; i < SplitIDs.length; i++) {
if($(this).attr('id') == SplitIDs[i]){
$("#grid img #"+$(this).attr('id')+":first").remove();
}
}
});
I would suggest to use some other attribute than class, eg. 'data-type'.
With the collected attribute values (e.g. 'types' array) do:
var $grid = $('#grid');
// iterate over collected types
types.forEach(function(type)) {
// find within $grid the first <img> with data-type == type and remove it from DOM
$grid.find('img[data-type="' + type + '"]:eq(0)').remove();
}
You could also do all in one rush:
// iterate over source <img> set
$('.frame div img').each(function() {
// get current images type-attrib
var type = $(this).attr('data-type');
// find within $grid the first <img> with data-type == type and remove it from DOM
$grid.find('img[data-type="' + type + '"]:eq(0)').remove();
});
Try
$(function() {
var classes = $.map($(".frame div img"), function(v, k) {
return [$(v).attr("class")];
});
var d = [];
console.log($("#grid img").length);
$.each($("#grid img"), function(k, v) {
if ( classes.hasOwnProperty($(v).attr("class")) ) {
d.push(v); $("body").find($(d.slice(0, 1))).remove();
};
});
console.log($("#grid img").length);
});
jsfiddle http://jsfiddle.net/guest271314/yv95C/
I have a Function which makes an ajax call and then return a piece of html that is inserted into a table's td element. using element.innerHTML=ajaxResult; Now I want to access the elements in the ajaxResult that have the name attribute as special. So I do a document.getElementsByName('special') and expect to get 4-5 elements. But I actually get none.
This makes it impossible for me to access those elements and I am stuck. Please help me resolve this. Thanks in Advance!
I think this is related to the dom not reloading after I set innerHTML. But not sure how to reload it.
I am using IE8 in IE8 compatibility view and IE7 standards :(
EDIT
This is my function
function handleStateChange()
{
if(ajaxRequest.readyState==4 && ajaxRequest.status==200) {
var responseStr = ajaxRequest.responseText;
var splitResult = responseStr.split("$$$$$$$$$$$$$$$$$$$$");
var leftHtml= splitResult [0];
var rightHtml= splitResult [1];
document.getElementById("div1").innerHTML=leftHtml;
if(rightHtml !="") {
document.getElementById("div2").innerHTML=rightHtml;
}
if(splitResult.length >=3 ){
var appActionflag = splitResult [2];
document.getElementById("userAction").innerHTML=appActionflag;
}
if(splitResult.length >= 4 ){
var userId = splitResult [3];
document.getElementById("userId").innerHTML=userId;
}
reverseDNASwitch();
var grpList = document.getElementsByName('parmGrpId');
alert('javascript is working! Found:'+grpList.length);
for(var i=0;i<grpList.length;i++){
alert('Got GroupId: '+ (i));
var grpTd = grpList[i];
grpTd.innnerHTML='Hi';
}
}
}
If the table cell you're adding to is, itself, in the DOM, that should work. (And so I may have to delete this answer; originally I thought document.getElementsByName had been deprecated, but I was mistaken). Here's an example using getElementsByName:
Live Copy | Live Source
(function() {
// Get the target
var target = document.getElementById("target");
// Dynamically add content
target.innerHTML =
'<div name="special">special 1</div>' +
'<div name="special">special 2</div>' +
'<div name="special">special 3</div>';
// Get those elements
var list = document.getElementsByName("special");
// Prove we got them
var p = document.createElement('p');
p.innerHTML = "Found " + list.length + " 'special' elements";
document.body.appendChild(p);
})();
Of course, because it's a function of document, that will find all of the elements with name="special", not just the ones you added to the table cell.
The above does not work on IE if the elements aren't allowed to have the name attribute. So for instance, if you look for getElementsByName("special"). it will ignore <div name="special"> but find <input name="special">, because name is not a valid attribute for div elements. Details in this MSDN article. Worse, IE will include elements whose id matches, even though of course that has nothing to do with name. sigh
Unless you need to support IE7 and earlier (e.g., unless you're developing for China), you can use Element#querySelectorAll with the selector '[name="special"]'. That will look only within the element for elements that use that name attribute.
Example: Live Copy | Live Source
(function() {
// Get the target
var target = document.getElementById("target");
// Dynamically add content
target.innerHTML =
'<div name="special">special 1</div>' +
'<div name="special">special 2</div>' +
'<div name="special">special 3</div>';
// Get those elements
var list = target.querySelectorAll('[name="special"]');
// Prove we got them
var p = document.createElement('p');
p.innerHTML = "Found " + list.length + " 'special' elements";
document.body.appendChild(p);
})();
If you need to support IE7 or earlier, you might look at this other Stack Overflow question and my answer to it. The question points to this article about adding querySelectorAll to document, and my answer to the question talks about how to emulate that at an element-specific level.
So combining the code from that article with my answer to the other question and the examples above, we get:
Live Copy | Live Source
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<div id="target"></div>
<script>
(function() {
// IE7 support for querySelectorAll. Supports multiple / grouped selectors and the attribute selector with a "for" attribute. http://www.codecouch.com/
if (!document.querySelectorAll) {
(function(d, s) {
d=document, s=d.createStyleSheet();
d.querySelectorAll = function(r, c, i, j, a) {
a=d.all, c=[], r = r.replace(/\[for\b/gi, '[htmlFor').split(',');
for (i=r.length; i--;) {
s.addRule(r[i], 'k:v');
for (j=a.length; j--;) a[j].currentStyle.k && c.push(a[j]);
s.removeRule(0);
}
return c;
}
})();
}
var qsaWorker = (function() {
var idAllocator = 10000;
function qsaWorkerShim(element, selector) {
var needsID = element.id === "";
if (needsID) {
++idAllocator;
element.id = "__qsa" + idAllocator;
}
try {
return document.querySelectorAll("#" + element.id + " " + selector);
}
finally {
if (needsID) {
element.id = "";
}
}
}
function qsaWorkerWrap(element, selector) {
return element.querySelectorAll(selector);
}
// Return the one this browser wants to use
return document.createElement('div').querySelectorAll ? qsaWorkerWrap : qsaWorkerShim;
})();
// Get the target
var target = document.getElementById("target");
// Dynamically add content
target.innerHTML =
'<div name="special">special 1</div>' +
'<div name="special">special 2</div>' +
'<div name="special">special 3</div>';
// Get those elements
var list = qsaWorker(target, '[name="special"]');
// Prove we got them
var p = document.createElement('p');
p.innerHTML = "Found " + list.length + " 'special' elements";
document.body.appendChild(p);
})();
</script>
</body>
</html>
Which works in IE7.
As an option for your specific scenario, where you want to get elements with a specific attribute (and value), you can use a function like this:
function getElementsByAttribute(options) {
/*if (container.querySelectorAll) {
var selector = '';
if (options.tagFilter) {
selector += options.tagFilter;
}
selector += '[' + options.attr;
if (options.val) {
selector += '="' + options.val.replace(/"/g, '\\"') + '"';
}
selector += ']';
return Array.prototype.slice.call(options.container.querySelectorAll(selector));
}*/
var elements = options.container.getElementsByTagName(options.tagFilter || "*"),
ret = [],
i, cur,
matches = (function () {
if (options.val) {
return function (el) {
return el.getAttribute(options.attr) === options.val;
};
} else {
return function (el) {
return el.hasAttribute(options.attr);
};
}
})();
for (i = 0; i < elements.length; i++) {
cur = elements[i];
if (matches(cur)) {
ret.push(cur);
}
}
return ret;
}
And you call it like:
window.onload = function () {
var contain = document.getElementById("container"),
els = getElementsByAttribute({
container: contain,
attr: "name",
val: "special",
tagFilter: ""
});
console.log("els", els);
};
DEMO: http://jsfiddle.net/cxq6t/1/
(I kept in my original logic for supporting querySelectorAll, but proved not to work in old IE with invalid attributes, per the comments)
The object you pass to the function accepts:
container: containing element to look through
attr: the attribute to look for
val: optional value to match against
tagFilter: optional filter for the tagName of matched elements
I tested in IE7/8 to see if the <div name="special"> would match, and it does. As well as the other <input />s.
If you ever wanted to expand the selector to be more complicated things like what querySelectorAll supports, you could use a polyfill like T.J.Crowder's. But this seems to get the job done.
When i create an element from a HTML String with zepto.js like this:
element = $("<ul />", {id:"myID"});
console.log(element);
the id "myID" does not get added to the element. The console output is this:
[<ul></ul>]
According to http://zeptojs.com/ -> $() it should get an id:
>// create element with attributes:
>$("<p />", { text:"Hello", id:"greeting", css:{color:'darkblue'} })
>//=> <p id=greeting style="color:darkblue">Hello</p>
Any idea what goes wrong? Or could this be a bug?
Edit:
I kind of solved this myself like this:
element.attr('id', 'myID');
Allthough it would be nicer not to take one extra step like this...
It seems in version Zepto.js (1.0rc1) this api was not introduced in.
See line 152 and line 100-108 in tag v1.0rc1
dom = zepto.fragment(selector.trim(), RegExp.$1), selector = null
zepto.fragment = function(html, name) {
if (name === undefined) name = fragmentRE.test(html) && RegExp.$1
if (!(name in containers)) name = '*'
var container = containers[name]
container.innerHTML = '' + html
return $.each(slice.call(container.childNodes), function(){
container.removeChild(this)
})
}
and line 167 and line 110-128 in master
dom = zepto.fragment(selector.trim(), RegExp.$1, context), selector = null
zepto.fragment = function(html, name, properties) {
if (html.replace) html = html.replace(tagExpanderRE, "<$1></$2>")
if (name === undefined) name = fragmentRE.test(html) && RegExp.$1
if (!(name in containers)) name = '*'
var nodes, dom, container = containers[name]
container.innerHTML = '' + html
dom = $.each(slice.call(container.childNodes), function(){
container.removeChild(this)
})
if (isPlainObject(properties)) {
nodes = $(dom)
$.each(properties, function(key, value) {
if (methodAttributes.indexOf(key) > -1) nodes[key](value)
else nodes.attr(key, value)
})
}
return dom
}
Also read this issue. Maybe it will be introduced in at time of a big 1.0.
And now, before the api can work, you can do this with the below code:
element = $("<ul />").attr({id:"myID"});
jQuery: how to change tag name?
For example:
<tr>
$1
</tr>
I need
<div>
$1
</div>
Yes, I can
Create DOM element <div>
Copy tr content to div
Remove tr from dom
But can I make it directly?
PS:
$(tr).get(0).tagName = "div";
results in DOMException.
You can replace any HTML markup by using jQuery's .replaceWith() method.
example: http://jsfiddle.net/JHmaV/
Ref.: .replaceWith
If you want to keep the existing markup, you could use code like this:
$('#target').replaceWith('<newTag>' + $('#target').html() +'</newTag>')
No, it is not possible according to W3C specification: "tagName of type DOMString, readonly"
http://www.w3.org/TR/DOM-Level-2-Core/core.html
Where the DOM renameNode() Method?
Today (2014) no browser understand the new DOM3 renameNode method (see also W3C)
check if run at your bowser: http://jsfiddle.net/k2jSm/1/
So, a DOM solution is ugly and I not understand why (??) jQuery not implemented a workaround?
pure DOM algorithm
createElement(new_name)
copy all content to new element;
replace old to new by replaceChild()
is something like this,
function rename_element(node,name) {
var renamed = document.createElement(name);
foreach (node.attributes as a) {
renamed.setAttribute(a.nodeName, a.nodeValue);
}
while (node.firstChild) {
renamed.appendChild(node.firstChild);
}
return node.parentNode.replaceChild(renamed, node);
}
... wait review and jsfiddle ...
jQuery algorithm
The #ilpoldo algorithm is a good start point,
$from.replaceWith($('<'+newname+'/>').html($from.html()));
As others commented, it need a attribute copy ... wait generic ...
specific for class, preserving the attribute, see http://jsfiddle.net/cDgpS/
See also https://stackoverflow.com/a/9468280/287948
The above solutions wipe out the existing element and re-create it from scratch, destroying any event bindings on children in the process.
short answer: (loses <p/>'s attributes)
$("p").wrapInner("<div/>").children(0).unwrap();
longer answer: (copies <p/>'s attributes)
$("p").each(function (o, elt) {
var newElt = $("<div class='p'/>");
Array.prototype.slice.call(elt.attributes).forEach(function(a) {
newElt.attr(a.name, a.value);
});
$(elt).wrapInner(newElt).children(0).unwrap();
});
fiddle with nested bindings
It would be cool to copy any bindings from the at the same time, but getting current bindings didn't work for me.
To preserve the internal content of the tag you can use the accessor .html() in conjunction with .replaceWith()
forked example: http://jsfiddle.net/WVb2Q/1/
Inspired by ericP answer, formatted and converted to jQuery plugin:
$.fn.replaceWithTag = function(tagName) {
var result = [];
this.each(function() {
var newElem = $('<' + tagName + '>').get(0);
for (var i = 0; i < this.attributes.length; i++) {
newElem.setAttribute(
this.attributes[i].name, this.attributes[i].value
);
}
newElem = $(this).wrapInner(newElem).children(0).unwrap().get(0);
result.push(newElem);
});
return $(result);
};
Usage:
$('div').replaceWithTag('span')
Working pure DOM algorithm
function rename_element(node, name) {
let renamed = document.createElement(name);
Array.from(node.attributes).forEach(attr => {
renamed.setAttribute(attr.name, attr.value);
})
while (node.firstChild) {
renamed.appendChild(node.firstChild);
}
node.parentNode.replaceChild(renamed, node);
return renamed;
}
You could go a little basic. Works for me.
var oNode = document.getElementsByTagName('tr')[0];
var inHTML = oNode.innerHTML;
oNode.innerHTML = '';
var outHTML = oNode.outerHTML;
outHTML = outHTML.replace(/tr/g, 'div');
oNode.outerHTML = outHTML;
oNode.innerHTML = inHTML;
To replace the internal contents of multiple tags, each with their own original content, you have to use .replaceWith() and .html() differently:
http://jsfiddle.net/kcrca/VYxxG/
JS to change the tag name
/**
* This function replaces the DOM elements's tag name with you desire
* Example:
* replaceElem('header','ram');
* replaceElem('div.header-one','ram');
*/
function replaceElem(targetId, replaceWith){
$(targetId).each(function(){
var attributes = concatHashToString(this.attributes);
var replacingStartTag = '<' + replaceWith + attributes +'>';
var replacingEndTag = '</' + replaceWith + '>';
$(this).replaceWith(replacingStartTag + $(this).html() + replacingEndTag);
});
}
replaceElem('div','span');
/**
* This function concats the attributes of old elements
*/
function concatHashToString(hash){
var emptyStr = '';
$.each(hash, function(index){
emptyStr += ' ' + hash[index].name + '="' + hash[index].value + '"';
});
return emptyStr;
}
Related fiddle is in this link
Since replaceWith() didn't work for me on an element basis (maybe because I used it inside map()), I did it by creating a new element and copying the attributes as needed.
$items = $('select option').map(function(){
var
$source = $(this),
$copy = $('<li></li>'),
title = $source.text().replace( /this/, 'that' );
$copy
.data( 'additional_info' , $source.val() )
.text(title);
return $copy;
});
$('ul').append($items);
Take him by the word
Taken the Question by Word "how to change tag name?" I would suggest this solution:
If it makes sense or not has to be decided case by case.
My example will "rename" all a-Tags with hyperlinks for SMS with span tags. Maintaining all attributes and content:
$('a[href^="sms:"]').each(function(){
var $t=$(this);
var $new=$($t.wrap('<div>')
.parent()
.html()
.replace(/^\s*<\s*a/g,'<span')
.replace(/a\s*>\s*$/g,'span>')
).attr('href', null);
$t.unwrap().replaceWith($new);
});
As it does not make any sense to have a span tag with an href attribute I remove that too.
Doing it this way is bulletproof and compatible with all browsers that are supported by jquery.
There are other ways people try to copy all the Attributes to the new Element, but those are not compatible with all browsers.
Although I think it is quite expensive to do it this way.
Jquery plugin to make "tagName" editable :
(function($){
var $newTag = null;
$.fn.tagName = function(newTag){
this.each(function(i, el){
var $el = $(el);
$newTag = $("<" + newTag + ">");
// attributes
$.each(el.attributes, function(i, attribute){
$newTag.attr(attribute.nodeName, attribute.nodeValue);
});
// content
$newTag.html($el.html());
$el.replaceWith($newTag);
});
return $newTag;
};
})(jQuery);
See : http://jsfiddle.net/03gcnx9v/3/
Yet another script to change the node name
function switchElement() {
$element.each(function (index, oldElement) {
let $newElement = $('<' + nodeName + '/>');
_.each($element[0].attributes, function(attribute) {
$newElement.attr(attribute.name, attribute.value);
});
$element.wrapInner($newElement).children().first().unwrap();
});
}
http://jsfiddle.net/rc296owo/5/
It will copy over the attributes and inner html into a new element and then replace the old one.
$(function(){
$('#switch').bind('click', function(){
$('p').each(function(){
$(this).replaceWith($('<div/>').html($(this).html()));
});
});
});
p {
background-color: red;
}
div {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Hello</p>
<p>Hello2</p>
<p>Hello3</p>
<button id="switch">replace</button>
You can use this function
var renameTag = function renameTag($obj, new_tag) {
var obj = $obj.get(0);
var tag = obj.tagName.toLowerCase();
var tag_start = new RegExp('^<' + tag);
var tag_end = new RegExp('<\\/' + tag + '>$');
var new_html = obj.outerHTML.replace(tag_start, "<" + new_tag).replace(tag_end, '</' + new_tag + '>');
$obj.replaceWith(new_html);
};
ES6
const renameTag = function ($obj, new_tag) {
let obj = $obj.get(0);
let tag = obj.tagName.toLowerCase();
let tag_start = new RegExp('^<' + tag);
let tag_end = new RegExp('<\\/' + tag + '>$');
let new_html = obj.outerHTML.replace(tag_start, "<" + new_tag).replace(tag_end, '</' + new_tag + '>');
$obj.replaceWith(new_html);
};
Sample code
renameTag($(tr),'div');
Try this one also. in this example we can also have attributes of the old tag in new tag
var newName = document.querySelector('.test').outerHTML.replaceAll('h1', 'h2');
document.querySelector('.test').outerHTML = newName;
<h1 class="test">Replace H1 to H2</h1>