addClass to variable and append jQuery - javascript

I'm having some problems when trying to add a class to a variable and then append this to another div. When I do this, the text appears but without the class I am trying to add to it. I am doing all of this with jQuery.
This is the code:
var names = $(this).attr('name');
var description = $(this).attr('description');
var url = $(this).attr('url');
$(names).addClass("nam");
$(div1).append( names + " " + description + " " + url);
});
I guess I am doing something wrong but can't see where.

You are creating a jQuery wrapper for name and adding a class to it but then you are appending the previous string reference instead of the jQuery wrapper to which the class was added.
Also you can't add class to a text node so try wrapping it with a span element(if name is not a html content like <span>some name</span>)
var names = $('<span />', {
text : $(this).attr('name'),
'class' : 'nam'
})
var description = $(this).attr('description');
var url = $(this).attr('url');
$(div1).append( names).append( " " + description + " " + url);
});

First off for this answer I am assuming we're using an xml string of the format you provided in your comment on op. Note - I did correct the syntax of the string to remove the extraneous semi colons.
var xmlstring = '<Blogs> <blog name="number1" description="1" url=" 1.com/"/> <blog name="number2" description="2" url="2.com/"/> <blog name="number3" description="3" url="3.com;" />" </Blogs>'
Now we can parse this string as expected into a jQuery object and use mostly as expected:
var $doc = $($.parseXML(xmlstring));
I'm assuming in your original example that this blog refers to one of these sub blogs so I'm going to say for my example:
var $this = $doc.find("blog:eq(2)");//the blog name=number3 in your example
//OR
var $this = $(this);//useful so we dont keep rewrapping
Okay so now we have our blog ($this) and we can append the contents to div1 as follows:
var names = $("<span>", {text:$this.attr('name'), 'class': 'nam'});
var description = $this.attr('description');
var url = $this.attr('url');
$(div1).append( names, description + " " + url);//as names is a span element
I tested this on an empty div and it produced the following outerhtml:
"<div><span class="nam">number3</span>3 3.com;</div>"
Hope this helped, I tried to explain steps because I'm not sure where what you're doing was deviating.

Related

jQuery append implementation is breaking

So I have this code that I am trying to alter –
Original:
jQuery(document).ready(function() {
var name = '';
var firstLastName = '[[T6:[[E48:[[S334:fr-id]]-[[S334:px]]:cons.first_name]]]] [[T6:[[E48:[[S334:fr-id]]-[[S334:px]]:cons.last_name]]]]';
var screenname = '[[T6:[[S48:0:screenname]]]]';
if (screenname) {
name = screenname;
} else {
name = firstLastName;
}
var splitName = name.split('');
var nameCheck = splitName[splitName.length-1];
jQuery('#personal_page_header h2').html("Support " + name + "'s Fundraiser" );
});
someone wrote this up and are no longer here, and what I'm trying to do now is figure out how to instead of replace the existing text, add to it.
So right now what this code does is it replaces the h2 content with the constituents registered name, or screenname.
What I'm trying to do now is append to that so that it will say something like
<h2>
Welcome to my fundraiser
<br/>
"Support" + name + "'s Fundraiser"
</h2>
but unfortunately what I tried breaks the code and stops it from working.
what I tried to do is this:
jQuery('#personal_page_header h2').append('<span><br />"Support " + name + "'s Fundraiser"</span>' );
I've tried to do a variety of other things that gave the same unsuccessful result.
Any help would be really appreciated!
Thanks
This should work for you:
jQuery('#personal_page_header h2').append("<span><br/>Support " + name + "'s Fundraiser</span>");
You've just got your quotations a little out of place.
You need to concatenate your code correctly, so if you'd like to keep the " use ' to concatenate. Further you need to escape the ' inside the string with \:
jQuery('#personal_page_header h2')
.append('<span><br />"Support ' + name + '\'s Fundraiser"</span>');

jQuery .html() function removing text

I am trying to edit the div's text, but when i use my function to update the rowcount, everytime the text vanihes completely. Would by nice if you could also explain why.
Thanks in advance.
My update function:
var rowCountF = $('#tablef tr').length;
var rowCountV = $('#tablev tr').length;
var ftext = "Teilnehmer (" + String(rowCountF) + ")";
var vtext = "Teilnehmer (" + String(rowCountV) + ")";
$("#divf").html(ftext);
$("#divv").html(vtext);
My div layer:
<div id="divf"class="tableheader"> <h2>Teilnehmer</h2> </div>
Code for divf:
<div id="divf"class="tableheader"> <h2>Teilnehmer</h2> </div>
You are actually replacing the contents of the div itself with your text. This means the heading disappears and there is only plain text.
Probably you wanted to replace the heading contents:
$("#divf h2").html(ftext);
$("#divv h2").html(vtext);
This will select the h2 elements inside the divs and hence will update only the text inside the headings.
The result will look like the following:
<div id="divf"class="tableheader"> <h2>Teilnehmer (987)</h2> </div>
<div id="divf"class="tableheader"> <h2>Teilnehmer (123)</h2> </div>
.html() sets the HTML, meaning it replaces anything that's currently there. If you want to add to the HTML, you'll need to set the HTML to what's already there plus what you're adding, like so:
var rowCountF = $('#tablef tr').length;
var rowCountV = $('#tablev tr').length;
var ftext = "Teilnehmer (" + rowCountF + ")";
var vtext = "Teilnehmer (" + rowCountV + ")";
//Get already-existing HTML
var divfHtml = $("#divf").html();
var divvHtml = $("#divv").html();
//Set the new HTML to the existing + the new text
$("#divf").html(divfHtml + ftext);
$("#divv").html(divvHtml + vtext);
If you only want to replace the heading, then just target the <h2> as Martin Zikmund suggested in his answer.
You need to reference the h2 for the div. using .html() will replace ALL of the html inside the #divf which in this case means it will replace the h2
$("#divf h2").html(ftext);
$("#divv h2").html(vtext);
Example: https://jsfiddle.net/qhef0toc/3/

Javascript not able to replace text with new Text with html

I trying to replace text with new text inside a html tag like:
text = " hello how are you? " ;
newText = "<h1>hello how are you? </h1> " ;
This is my code:
//replacer holds the html element
var replacer = document.getElementById("#"+id);
var newElement = "<span style='font-size:100px;' id='one4'>"+selectedinnerText+"</span>";
//selectedinnerText holds the text to be replaced
alert(selectedinnerText + " "+ newElement );
//This below line is not working properly
replacer.innerHTML = replacer.innerHTML.replace(selectedinnerText,newElement);
Your issue is, when you are getting an element by its id in JavaScript, you do not need # infront of the id name.
var replacer = document.getElementById(id);
So, the reason why you cannot set the innerHTML of the replacer element is because there is no element stored in the variable right now.
The correct code should be
var replacer = document.getElementById(id);// no # needed here
var newElement = "<span style='font-size:100px;' id='one4'>"+selectedinnerText+"</span>";
alert(selectedinnerText + " "+ newElement );
replacer.innerHTML = replacer.innerHTML.replace(selectedinnerText,newElement);

Parsing in jquery

I am trying to parse what I am getting JQuery to show data ! I am consuming data from an API , but I am getting an error .
Can I do a Loop on JQuery this way ?
$.each(data.results, function (i, item) { // on this line
var Name = item.name;
var Date = item.auditInfo.dateCreated;
var Creator = item.creator.display;
$htmlstring.append($('<li/>').append('<p>Test</p>'));
$htmlstring.append("<div class='title'> Info : "
Name + Date + Creator "</div>");
}); $('#afficher').html($htmlstring);
I am sharing code on JSFiddle (Check drug_omrsRestCall function ) :
http://jsfiddle.net/zTXyq/23/
As #adeneo commented on the question, the concept is right but you should be careful about what element you are appending HTML content to.
With this snippet of your code:
$htmlstring.append("<div class='title'> Info : "
Name + Date + Creator "</div>");
(BTW, it is missing two plus signs for a correct concatenation, I hope that's not the error you are getting).
you append a DIV to the UL and you actually want to append it to the LI, for example:
$('<li />').append("<p>Test</p>")
.append("<div class='title'> Info : " + Name + Date + Creator + "</div>")
.appendTo($htmlstring);
Check this fiddle for a working solution of your issue:
http://jsfiddle.net/d3dcj/2/

Extract text from a ajax response which contains <tag>

I have write a little piece of code to retrieve news from rss page. Here is the code :
this.loadRecentNews = function loadRecentNews() {
$.get("http://rss.nytimes.com/services/xml/rss/nyt/GlobalHome.xml", function (data) {
$(data).find("item").each(function () {
var el = $(this);
console.log("------------------------");
console.log("Title : " + el.find("title").text());
console.log("Link : " + el.find("link").text());
console.log("Description: " + el.find("description").text());
console.log("Date: " + el.find("pubDate").text());
});
});
};
Here is the output :
Title : Example of title
Link : http://www.example.com
Description : Example of <<bb>>Description</b> containing <> tag..
Date : Example of date
My problem is that i want to extract only the text of the Description value to build a new Json object which contain this text.
How can i do to extract only the text without <> values ?
Seeing as you're using jQuery, you can use its .text() method.
var beforeText = "Example of <b>Description</b>" ;
var afterText = $("<p>").html(beforeText).text() ;
This uses jQuery to make a new HTML element (that is never added to the page) and update its innerHTML and then use .text() to get the text only.
Another (riskier) option is a regex to replace anything between < and > with an empty string:
var afterText = beforeText.replace(/<[^>]*>+/g, "")

Categories