JQuery replace html element contents if ID begins with prefix - javascript

I am looking to move or copy the contents of an HTML element. This has been asked before and I can get innerHTML() or Jquery's html() method to work, but I am trying to automate it.
If an element's ID begins with 'rep_', replace the contents of the element after the underscore.
So,
<div id="rep_target">
Hello World.
</div>
would replace:
<div id="target">
Hrm it doesn't seem to work..
</div>​
I've tried:
$(document).ready(function() {
$('[id^="rep_"]').html(function() {
$(this).replaceAll($(this).replace('rep_', ''));
});
});​
-and-
$(document).ready(function() {
$('[id^="rep_"]').each(function() {
$(this).replace('rep_', '').html($(this));
});
​});​
Neither seem to work, however, this does work, only manual:
var target = document.getElementById('rep_target').innerHTML;
document.getElementById('target').innerHTML = target;
Related, but this is only text.
JQuery replace all text for element containing string in id

You have two basic options for the first part: replace with an HTML string, or replace with actual elements.
Option #1: HTML
$('#target').html($('#rep_target').html());
Option #2: Elements
$('#target').empty().append($('#rep_target').children());
If you have no preference, the latter option is better, as the browser won't have to re-construct all the DOM bits (whenever the browser turns HTML in to elements, it takes work and thus affects performance; option #2 avoids that work by not making the browser create any new elements).
That should cover replacing the insides. You also want to change the ID of the element, and that has only one way (that I know)
var $this = $(this)
$this.attr($this.attr('id').replace('rep_', ''));
So, putting it all together, something like:
$('[id^="rep_"]').each(function() {
var $this = $(this)
// Get the ID without the "rep_" part
var nonRepId = $this.attr('id').replace('rep_', '');
// Clear the nonRep element, then add all of the rep element's children to it
$('#' + nonRepId).empty().append($this.children());
// Alternatively you could also do:
// $('#' + nonRepId).html($this.html());
// Change the ID
$this.attr(nonRepId);
// If you're done with with the repId element, you may want to delete it:
// $this.remove();
});
should do the trick. Hope that helps.

Get the id using the attr method, remove the prefix, create a selector from it, get the HTML code from the element, and return it from the function:
$('[id^="rep_"]').html(function() {
var id = $(this).attr('id');
id = id.replace('rep_', '');
var selector = '#' + id;
return $(selector).html();
});
Or simply:
$('[id^="rep_"]').html(function() {
return $('#' + $(this).attr('id').replace('rep_', '')).html();
});

From my question, my understanding is that you want to replace the id by removing the re-_ prefix and then change the content of that div. This script will do that.
$(document).ready(function() {
var items= $('[id^="rep_"]');
$.each(items,function(){
var item=$(this);
var currentid=item.attr("id");
var newId= currentid.substring(4,currentid.length);
item.attr("id",newId).html("This does not work");
alert("newid : "+newId);
});
});
Working Sample : http://jsfiddle.net/eh3RL/13/

Related

Move array of DOM elements to placeholders in page

I have a design received on my page with a set of placeholders such as:
<span id="ApplicationDate_" class="removeMe"></span>
Plus other many elements as well inside that html. These spans should be replaced by real inputs coming from another area on the page, such inputs look like:
<input type="text" id="ApplicationDate_48596977"/>
So basically what I need to do, is to get all input elements in an array, and then for each element, get its ID up to "_", and search for the span that equals that value, and replace it with this element, then remove all spans with class=removeMe, but I can't achieve it in code, below is what I have reached:
$(document).ready(function () {
var coll = $("input");
coll.each(function () {
var id = this.id; //getting the id here
var substringId = id.substring(0, id.indexOf('_') + 1); //getting the span id
this.appendTo("#" + substringId); //having problems here..
});
$(".removeMe").each(function () {
this.remove();
});
});
it tells me this.appendTo is not a function, any help or hint is much appreciated.
TL;DR - Just use:
$(".removeMe").replaceWith(function() {
return $("input[id^='" + this.id + "']");
});
Here's why:
this is a DOM element, but .appendTo() is a jQuery method. You probably just need to wrap this in a call to jQuery:
$(this).appendTo("#" + substringId);
That would place the <input> element inside the <span> like this:
<span id="ApplicationDate_" class="removeMe">
<input type="text" id="ApplicationDate_48596977"/>
</span>
But, then you call:
$(".removeMe").each(function () {
this.remove();
});
First, you would have the same problem as above - this is a DOM element, but .remove() is a jQuery method. Second, it would be better to just call $(".removeMe").remove() - wrapping it in a .each() is redundant. Third, that would remove the span, and the input along with it. That's not what you are trying to do is it?
If you want to replace the span with the input, use .replaceWith():
var coll = $("input");
coll.each(function () {
var substringId = this.id.substring(0, id.indexOf('_') + 1);
$("#" + substringId).replaceWith(this);
});
It seems like the whole thing could be rewritten, taking advantage of the attribute starts with selector, as:
$(".removeMe").replaceWith(function() {
return $("input[id^='" + this.id + "']");
});

Pin .data/.attr to particular id and class

I am trying to pin some data or attr to the editButton class, but only to the element of the given thisId.
It works with only class but when I add thisId as a second parameter it stops working. I also tried to use .find() but it also doesnt work.
What I am doing wrong?
<a href="#!" class="editButton" id="{{$comment->h_id}}" onClick="editComment({{$comment->h_id}}, `{{$comment->f_text}}`)">
<script>
function editComment(id, text){
var thisId = "#" + id;
$(".editButton", thisId).attr("PinComment", "some new comment");
alert($(".editButton", thisId).attr("PinComment"));
}
</script>
$(".editButton", thisId) is equivalent to $(thisId).find(".editButton"); either of the would work if and only if the elements matching $(".editButton") are descendants of the element matching $(thisId).
However, from your code snippet, both $(".editButton") and $(thisId) are same elements, so your usage of $(".editButton", thisId) doesn't work as you expect.
Read this to understand the API you are using better.
To solve your problem, you could go with this approach:
var selector = ".editButton" + thisId;
var element = $(selector);
element.attr("PinComment", "some new comment");
alert(element.attr("PinComment"));

js How to add href + text onclick

I need to pass (using javascript) text inside span to href
<div class='tableCell'><span>information</span></div>
<div class='tableCell'><span>contact</span></div>
<div class='tableCell'><span>about</span></div>
for example when i click to about link must be example.com/tag/about/
Here is my Answer. I'm using Javascript to manipulate the DOM to add a new element with the href equal to the inner text within the span element.
I hope you find this answer helpful.
Thanks.
var spans = document.getElementsByTagName('span')
var baseUrl = 'http://example.com/tag/'
for(var i=0; i<spans.length; i++)
{
var curElement = spans[i];
var parent = curElement.parentElement;
var newAElement = document.createElement('a');
var path = baseUrl+curElement.innerHTML;
newAElement.setAttribute('href', path);
newAElement.appendChild(curElement);
parent.appendChild(newAElement)
}
DEMO
The simplest way:
$( "span" ).click(function() {
var link = 'http://yousite.com/tag/'+ $(this).text().replace(/ /, "-")+"/";
window.location.href= link.toLowerCase();
});
DEMO
http://codepen.io/tuga/pen/yNyYPM
$(".tableCell span").click(function() {
var link = $(this).text(), // will provide "about"
href = "http://example.com/tag/"+link; // append to source url
window.location.href=href; // navigate to the page
});
You can try the above code
You do not have links but span in your html. However, you can get build the href you want and assign it to an existing link:
$('div.tableCell').click(function(){
var href = 'example.com/tag/' + $(this).find('span').text();
})
Lets work with pure javascript, I know you want to use jQuery but I am really sure too many people can't do this without looking in to web with pure javascript. So here is a good way.
You can follow it from jsFiddle
var objectList = document.getElementsByClassName("tableCell");
for(var x = 0; x < objectList.length; x++){
objectList[x].addEventListener('click', function(){
top.location.href = "example.com/tag/" + this.childNodes[0].innerHTML;
});
}
Lets work on the code,
var objectList = document.getElementsByClassName("tableCell");
now we have all element with the class tableCell. This is better than $(".tableCell") in too many cases.
Now objectList[x].addEventListener('click', function(){}); using this method we added events to each object.
top.location.href = "example.com/tag/" + this.childNodes[0].innerHTML; with this line if somebody clicks to our element with class: We will change the link to his first child node's text.
I hope it is useful, try to work with pure js if you want to improve your self.
Your Method
If you always are going to have the url start with something you can do something like this. The way it is set up is...
prefix + THE SPANS TEXT + suffix
spaces in THE SPANS TEXT will be converted to -
var prefix = 'http://example.com/tag/',
suffix = '/';
$('span').click(function () {
window.location.href = prefix + $(this).text().replace(' ', '-').trim().toLowerCase() + suffix;
//An example is: "http://example.com/tag/about-us/"
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='tableCell'><span>Information</span></div>
<div class='tableCell'><span>Contact</span></div>
<div class='tableCell'><span>About</span></div>
You can adjust this easily so if you want it to end in .html instead of /, you can change the suffix. This method will also allow you to make the spans have capitalized words and spaces.
JSBIN

jQuery remove certain tags from a string

I have a string where I want to remove all figure tags. I have tried the following:
var s = '<html><body>report content<figure id="fig2" data-contenttype="chart"><img src="chart.jpg"/><div>chart 1</div></figure><div>body content</div><figure id="fig2"><img src="chart2.jpg"/><div>chart 2</div></figure></body></html>';
var result = $(s).find('figure').remove();
The reason this does not work is that find does not find the figure elements because they have children. Does anyone know how I can remove all figure nodes (and everything inside them) and leave the rest of the html in tact?
Note the html is not in the DOM I need to do this via string manipulation. I don't want to touch the DOM.
You can wrap your string in a jQuery object and do some sort of a manipulation like this:
var removeElements = function(text, selector) {
var wrapped = $("<div>" + text + "</div>");
wrapped.find(selector).remove();
return wrapped.html();
}
USAGE
var removedString = removeElements('<html><body>report content<figure id="fig2" data-contenttype="chart"><img src="chart.jpg"/><div>chart 1</div></figure><div>body content</div><figure id="fig2"><img src="chart2.jpg"/><div>chart 2</div></figure></body></html>','figure');
The beauty of this approach is that you can specify a jquery selector which to remove.
Another approach for keeping html and body tag:
var s = '<html><body>report content<figure id="fig2" data-contenttype="chart"><img src="chart.jpg"/><div>chart 1</div></figure><div>body content</div><figure id="fig2"><img src="chart2.jpg"/><div>chart 2</div></figure></body></html>';
var $s = s.replace(/<figure>(.*)<\/figure>/g, "");
console.log($s)

Turn an anchor into a span?

What's the easiest way to turn an <a> into <span> keeping all the attributes and content? (except for perhaps the href).
.replaceWith() replaces the whole shebang.
You can iterate an element's attributes using the attributes property. You can copy an attribute using attribute.cloneNode(true). You can add that cloned attribute to another element's attributes collection with element.attributes.setNamedItem(attribute).
Here's a quick plugin that does it:
$.fn.cloneTo = function (target) {
// copies the attributes, html, and event handlers of the first element to each of
// the elements in the provided jQuery object or that match the provided selector
if (!target || !target.jquery) {
target = $(target);
}
if (this.length) {
$.each(this[0].attributes, function(i, attr) {
target.each(function(){
this.attributes.setNamedItem(attr.cloneNode(true));
});
});
$.each(this.data("events"), function(evt, handlers){
$.each(handlers, function(i, handler){
target.bind(evt, handler);
});
});
target.empty().append(this.contents());
}
return this;
};
Use it like this:
var span = $("<span>");
$("#myLink").cloneTo(span).replaceWith(span);
Working demo: http://jsfiddle.net/gLqZJ/2
Edit: Updated above to copy event handlers and to keep the descendent nodes untouched, rather than duplicating the HTML.
How about
$element.html(function(html) {
return html.replace(/<(\/?)a/gi, "<$1span"); // string manipulation might be faster, but you get the concept
});
That would save the attributes and content, but not any data and event handlers. If you need those for the descendants, you should remove the child nodes and append them to the new span.
EDIT: Sorry, I'm not that familiar with jQuery. The .html() method changes the innerHTML, not including the node itself. The function should be something like:
$element(s).each(function() {
var l = this.tagName.length + 1;
this.outerHTML = "<span"+this.outerHTML.slice(l, -l)+"span>";
});
Combine jQuery's replaceWith() and html() and copy attributes iteratively. Given your anchor tag has id #anchor:
$('#anchor').replaceWith(function() {
var span = $('<span/>');
$.each(this.attributes, function(){
span.attr(this.name, this.value);
});
return span.html($(this).html());
});
See updated jsFiddle for an example.

Categories

Resources