jQuery replaceWith() for HTML string - javascript

I am using filter() to select a list of elements then trying to replacing them by use of replaceWith(). The html is saved as string on a variable. It seem the replaceWith() is not working for me. When I log the variable content it shows the original string.
Is I know js objects are references. So, I was under the impression that replacing the selection will also replace element inside the string.
Here is the code
var content = '<div class="feature-box" contenteditable="false" data-sh-attr="%20title%3D%22jhk%22%20width%3D%224%22%20icon%3D%22thumbs-up%22" data-sh-content="kj"><div class="btn-panel"><a class="delete" href="#"><i class="fa fa-trash"> </i></a> <a class="edit" href="#"><i class="fa fa-pencil"> </i></a></div><div class="feature-icon-container"><i class="fa fa-thumbs-up main-icon"> </i></div><div class="feature-content"><h3>jhk</h3><div class="content">kj</div></div><div> </div></div><p>[block background_color="red" color="white"]Content of the block[/block]</p><p>This is an example page. It\'s different from a blog post because it will stay in one place and will show up in your site navigation (in most themes). Most people start with an About page that introduces them to potential site visitors. It might say something like this:</p><blockquote><p>Hi there! I\'m a bike messenger by day, aspiring actor by night, and this is my blog. I live in Los Angeles, have a great dog named Jack, and I like piƱa coladas. (And gettin\' caught in the rain.)</p></blockquote><p>...or something like this:</p><div class="feature-box" contenteditable="false" data-sh-attr="%20title%3D%22kk%22%20width%3D%224%22%20icon%3D%22thumbs-up%22" data-sh-content="kk"><div class="btn-panel"><a class="delete" href="#"><i class="fa fa-trash"> </i></a> <a class="edit" href="#"><i class="fa fa-pencil"> </i></a></div><div class="feature-icon-container"><i class="fa fa-thumbs-up main-icon"> </i></div><div class="feature-content"><h3>kk</h3><div class="content">kk</div></div><div> </div></div><blockquote><p>The XYZ Doohickey Company was founded in 1971, and has been providing quality doohickeys to the public ever since. Located in Gotham City, XYZ employs over 2,000 people and does all kinds of awesome things for the Gotham community.</p></blockquote><p>As a new WordPress user, you should go to your dashboard to delete this page and create new pages for your content. Have fun!</p>';
jQuery(content).filter('.feature-box').each(function(){
var $this = jQuery(this);
var attr = decodeURIComponent($this.data('sh-attr'));
var content = decodeURIComponent($this.data('sh-content'));
var shortcode = '[feature' + attr + ']' + content + '[/feature]';
$this.replaceWith(shortcode);
});
console.log(content);
jsFiddle to play with
http://jsfiddle.net/du8d45tt/

You are creating an dom structure and is modifying that dom structure, which won't modify the original string
To get the updated html, you need to get the updated content of the dom structure.
var $tmp = $('<div />', {
html: content
})
$tmp.find('.feature-box').each(function () {
var $this = jQuery(this);
var attr = decodeURIComponent($this.data('sh-attr'));
var content = decodeURIComponent($this.data('sh-content'));
var shortcode = '[feature' + attr + ']' + content + '[/feature]';
$this.replaceWith(shortcode);
});
var replaced = $tmp.html()
console.log(replaced);
Demo: Fiddle

You don't actually assign the updated html anywhere. $this.replaceWith(shortCode); updates $this not content.
You can use .html() to get the updated content and assign it back.
content = $this.replaceWith(shortcode).html();
Due to the asynchronous nature of the jQuery each method, it runs a callback, you should also have the console.log within the each function.
jQuery(content).filter('.feature-box').each(function(){
var $this = jQuery(this);
var attr = decodeURIComponent($this.data('sh-attr'));
var content = decodeURIComponent($this.data('sh-content'));
var shortcode = '[feature' + attr + ']' + content + '[/feature]';
content = $this.replaceWith(shortcode).html();
console.log(content);
});

Strings are immutable objects in JavaScript, so you need to overwrite it with another value:
content = jQuery('<div>', {html: content})
.find('.feature-box')
.replaceWith(function() {
var $this = jQuery(this);
var attr = decodeURIComponent($this.data('sh-attr'));
var content = decodeURIComponent($this.data('sh-content'));
return '[feature' + attr + ']' + content + '[/feature]';
})
.end()
.html();
This also uses .replaceWith(fn) syntax as a handy shortcut for .each() and using .replaceWith() inside.

Related

Empty Quotes In jQuery Variable

I'm trying to add a link after a black of text. I can get them to render just fine, but the link href tag just disappears.
var eventstuff = data.text;
var eventElement = $("<div class='well well-sm eventsWells'>");
var deleteButton = $("<div class='panel'><a style='float:right; color:#348CD9; margin-top:3px;' href='' ng-click='deleteEvent("+key+")'>DELETE</a></div>");
eventElement.html(eventstuff).append(deleteButton);
eventsList.append(eventElement);
But the html just shows:
<a style="float:right; color:#348CD9; margin-top:3px;" href ng-click="deleteEvent(-KAY7j7_deUWLjhDbaQ5)">DELETE</a>
and clicking the link takes me to /# (using Angular).
I've tried using href='#' and putting return false at the end, which also didn't work, it still redirected to /#.
I've also tried escaping the quotation marks, and removing the href, both of which don't work. Any ideas?
This might because of deleteEvent(-KAY7j7_deUWLjhDbaQ5).
Correct onclick when you are passing string type parameter should be like this:
deleteEvent('-KAY7j7_deUWLjhDbaQ5')
^ ^ // ==>quotes are requried
This you can achieve by using following like:
var deleteButton = $("<div class='panel'><a style='float:right; color:#348CD9; margin-top:3px;' href='' ng-click='deleteEvent(\'"+key+"\')'>DELETE</a></div>");
Updates
You need to add $compile service here, that will bind the angular directives like ng-click to your controller scope. See following:
var eventstuff = data.text;
var eventElement = $("<div class='well well-sm eventsWells'>");
var deleteButton = $("<div class='panel'><a style='float:right; color:#348CD9; margin-top:3px;' href='' ng-click='deleteEvent(\'"+key+"\')'>DELETE</a></div>");
$compile(deleteButton)($scope); //here
$compile(eventElement)($scope); //here
eventElement.html(eventstuff).append(deleteButton);
eventsList.append(eventElement);
You can try like this
href='javascript:void(0);' ng-click='deleteEvent(\""+key+\"")'

Adding tags to HTML using javascript

I have HTML produced from XSLT that looks like:
<span id="text">It's like what Sir Ian McKellan told me the day I sold my boat to Karl Lagerfeld: <span id="quote">Parting is such sweet sorrow.</span></span>
I'm trying to use javascript to parse it such that extra tags are added to mark the context around the quote. The goal is to give users the option whether or not to display the quote plus context or just the quotation. The end result would be, e.g.,
<span id="text"><span id="preContext">It's like what Sir Ian McKellan told me the day I sold my boat to Karl Lagerfeld: </span><span id="quote">Parting is such sweet sorrow.</span></span>
This way, it would be simple to define the style.display of preContext as none. I've tried using insertAdjacentHTML; for example,
document.getElementById("text").insertAdjacentHTML('afterbegin', "<span id='preContext'>");
document.getElementById("quote").insertAdjacentHTML('beforebegin', "</span>");
But, as I've discovered, insertAdjacentHTML can insert nodes but not individual tags. The above gets me <span id="text"><span id="preContext"></span>It's like. . .
Is this possible in javascript, or does this need to be done in XSLT? (PS: I don't want to use JQuery. . )
Working example: http://jsfiddle.net/vcSFR/1/
This code gets the first textNode, wraps it in a span, and then swaps the original first text node for the new span.
var oDiv = document.getElementById("text");
var firstText = "";
for (var i = 0; i < oDiv.childNodes.length; i++) {
var curNode = oDiv.childNodes[i];
if (curNode.nodeName === "#text") {
firstText = curNode.nodeValue;
break;
}
}
firstTextWrapped = '<span id="preContext">' + firstText + '</span>';
oDiv.innerHTML = oDiv.innerHTML.replace(firstText, firstTextWrapped);
Thanks to https://stackoverflow.com/a/6520270/940252 for the code to get the first textNode.

JQuery inccorectly append created JQuery object

folks.
I have question about Jquery.append() method. I nothing found in documentation about my problem (or I doesn't search enough).
I have following HTML markup.
<li class="active bug-droppable" bugId="1">
<a href="#">Super Bug 1
<span class="badge badge-primary">2</span>
</a>
</li>
I using bootstrap and want to add span tag which represent icon to anchor tag.
I do following and this works good enough. But I want to create function which allow customize icon. ("this" references to "li")
var PLUS_ICON = '<span class="pull-right glyphicon glyphicon-plus-sign medium-icon"></span>';
$(this).find("a").append(PLUS_ICON);
I tried following, it's looks similar but it doesn't work.
var ICON_DUMMY = '<span class="glyphicon medium-icon"></span>'
var ICON_PLUS_CLASS = ".glyphicon-plus-sign";
var PULL_RIGHT = ".pull-right";
var $icon = $(ICON_DUMMY).addClass(ICON_PLUS_CLASS).addClass(PULL_RIGHT);
$(this).find("a").append($icon);
Who can explain why second case doesn't work?
Thanks for your time.
Because you have a period in front of the class name. That is invalid for class attribute.
Change like so and it should work.
var ICON_PLUS_CLASS = "glyphicon-plus-sign";
var PULL_RIGHT = "pull-right";
try
var ICON_PLUS_CLASS = "glyphicon-plus-sign";
var PULL_RIGHT = "pull-right";
var $icon = $('<span class="glyphicon medium-icon"></span>').addClass(ICON_PLUS_CLASS).addClass(PULL_RIGHT);

Self written toc jQuery function: jump to link target and show corresponding element

I generate dynamically a toc for elements of class=faqQuestion.
The answer resides in a class=faqAnswer element which is hidden by default.
By clicking on class=faqQuestion entry it will show up with
$(this).next(".faqAnswer").slideToggle(300);
Everything works as expected.
What I want: by clicking on a toc link i will jump to the target faqQuestion element and show the corresponding faqAnweser element.
The way I generate the toc:
$(document).ready(function(){
var url = window.location.pathname;
$('<ol />').prependTo('#toc')
$(".faqQuestion").each(function(i) {
var current = $(this);
current.attr("id", "entry" + i);
$("#toc ol").append("<li class=\"faqToc\"><a id='link" + i + "' href='" + url + "#entry" +
i + "' entry='" + current.attr("tagName") + "'>" +
current.html() + "</a></li>");
});
This is what I tried, which will jump to the selected faqQuestion but the faqAnswer element is still hidden.
$(".faqToc").click(function(event){
$(this).next(".faqAnswer").slideToggle(300);
});
My problem is this - at least I think so - so I tried something like - which results in "undefined"
var url = $(this).prop("href");
alert(url);
Trying attr instead of prop returns also "undefined".
Can you point out my problem?
I'm trying to improve my Javascript and jQuery know how, so I don't want to use a toc-plugin.
Update: HTML looks like this:
<div id="toc">
<ol>
<li class="faqToc">
...
</li>
<li class="faqToc">
...
</li>
</div>
<p id="entry0" class="faqQuestion">...</p>
<div class="faqAnswer" style="display: none;">...</div>
<p id="entry1" class="faqQuestion">...</p>
<div class="faqAnswer" style="display: none;">...</div>
A very simple way would be to use the index() method since relationship between the TOC elements and the question/answer elements is 1 to 1.
$(".faqToc").click(function(event){
var index=$(this).index(); /* zero based index position of element within it's siblings*/
/* toggle answer element with same index */
$(".faqAnswer").eq(index).slideToggle(300);
});
jQuery API Reference : index()

jquery: "Exception thrown and not caught" in IE8, but works in other browsers

My code works fine in other browsers, but in IE8 I get "error on page" - and when I click that it says:
"Exception thrown and not caught Line: 16 Char: 15120 Code: 0
URI: http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"
I tried linking to jquery.js (rather than jquery.min.js) and to 1.5.1/jquery.min.js,
but problem still remains.
Can someone correct/improve my code for me, or guide me as to where to look. Thanks
<script type="text/javascript">
function fbFetch()
{
var token = "<<tag_removed>>&expires_in=0";
//Set Url of JSON data from the facebook graph api. make sure callback is set with a '?' to overcome the cross domain problems with JSON
var url = "https://graph.facebook.com/<<ID_REMOVED>>?&callback=?&access_token=" + token;
//Use jQuery getJSON method to fetch the data from the url and then create our unordered list with the relevant data.
$.getJSON(url, function(json)
{
json.data = json.data.reverse(); // need to reverse it as FB outputs it as earliest last!
var html = "<div class='facebook'>";
//loop through and within data array's retrieve the message variable.
$.each(json.data, function(i, fb)
{
html += "<div class='n' >" + fb.name;
html += "<div class='t'>" + (dateFormat(fb.start_time, "ddd, mmm dS, yyyy")) + " at " + (dateFormat(fb.start_time, "h:MMtt")) + "</div >";
html += "<div class='l'>" + fb.location + "</div >";
html += '<div class="i"><a target="_blank" title="opens in NEW window" href="https://www.facebook.com/pages/<<id_removed>>#!/event.php?eid=' + fb.id + '" >more info...</a></div>';
html += "</div >";
}
);
html += "</div>";
//A little animation once fetched
$('.facebookfeed').animate({opacity: 0}, 500, function(){
$('.facebookfeed').html(html);
});
$('.facebookfeed').animate({opacity: 1}, 500);
});
};
Does the code do the job in IE8 or does it break? The reason I ask is because if it works as expected you could just wrap it in a try{ } catch{ \\do nothing } block and put it down to another thing IE is rubbish at.
You may be better off creating an object for the creation of the facebook div. Something like...
var html = $('<div />');
html.attr('class', 'facebook');
Then in your each loop you can do this...
$('<div />').attr('class', 'n').append(fb.name).appendTo(html);
$('<div />').attr('class', 't').append etc...
Then append html to the facebookfeed object
Doing this may remove the scope for error when using single quotes and double quotes when joining strings together, which in turn may solve your issue in IE8
$('.facebookfeed').fadeOut(500, function(){
$(this).append(html).fadeIn(500);
});
Hope this helps!
UPDATE
The append method is used to add stuff to a jquery object. For more info see here
So to surround the div's as you mentioned in the comments you would do something like this...
var nDiv = $('<div />').attr('class', 'n').append(fb.name);
$('<div />').attr('class', 't').append(fb.somethingElse).appendTo(nDiv);
// etc
And then you would need to append that to the html div like so...
html.append(nDiv);
So that would give you
<div class="facebook">
<div class="n">
value of fb.name
<div class="t">
value of fb.somethingElse
</div>
</div>
</div>
So what you have done is created a new jquery object and appended to that, then appended that to the html object which you have then appended to the facebookfeed div. Confusing huh?!

Categories

Resources