Insert places Html in jQuery code - javascript

Hi i have a little problem.
I want use codes html to change style of texts,but i don't can import it into Jquery Scripts.
$('body').append($('<p>').html( <p id="text2">Data:<p>'Data:'+["Data"]));
How i have to do?

If you mean styling the object with css then here you go:
$('body').append($('<p>').css('cssproperty','value);
If you mean appending html to your object I would do:
var myNewHtmlP = $('<p id="text2">Data:<p>'Data:'+["Data"])');
myNewHtmlP.appendTo($('body'));

hey i think you search for this:
$('body').append( $('<p/>').attr('id', 'text2' ).html('myTestText'));
first you append the p tag, the slash is very important, after that the p tag get the id "text2" and after that you write the text 'myTestText' in the p tag

Related

Convert string to HTML in JavaScript

I have a string being sent to my JavaScript function from my C# code which has a text like:
Hi <b>Welcome to C#<sup>5.0</sup></b>
I'm populating a div with this string. I need this html content to be rendered in the screen with the bold and superscript applied as below
Hi Welcome to C#5.0
I tried the below it just displays the HTML tags as plain text
myfunction = function(data) {
var mytext = '<div>'+ data +'</div>;
$('#mydivid').after(mytext);
}
Is there any other solution neither like the one given here nor like this ?
Note: I cannot declare the string in a hidden variable in my .cshtml file within #HTML.Raw and again use it in my JavaScript.
I have tried using $.parseHTML but I got an error saying
$.parseHTML is not a function
Any solution other than the above solutions are welcome. Thanks in advance.
seems like nothing is wrong with your code. Check if some css is overriding the basic em and sup functionality.
for Example the default style of em is font-style: italic which chould be override by your css
Try like this
myfunction = function(data) {
$('#mydivid').html('<div>' + data + '</div>');
}
You listed JQuery in your tags so I figured this would help.
html = $.parseHTML( 'Hi <b>Welcome to C#<sup>5.0</sup></b>' );
Check out this JSFiddle
You can also do this if you want a javascript oneliner.
document.getElementById("mydivid").innerHTML="Hi <b>Welcome to C#<sup>5.0</sup></b>";

i wanted to change the font style of the content of a specific node after fetching and parsing the DOM tree

I have html for which I want to parse a specific node and change its content, along with making the font style of the new node value to italics. I am able to parse till the specific nodevalue but am not able to get how to change the fontstyle of the nodeValue.
In case of my problem
<html>
<head>
<script src="potrait.js"></script>
</head>
<body>
<p class="q">Here comes the count</p>
<ul class="q">
<li><p class="q" align="center">1</p></li>
</ul>
</body>
</html>
i want to change '1' to one(something), (something) should be in italics.
I get till 1 using the DOM method shown below
var list=document.getElementsByTagName('ul')
list[0].firstChild.nextSibling.childNodes[0].firstChild.nodeValue = "one(something)")
I am able to change the content but I am not able to get how to change (something) to italics.
Any guidance would be really appreciable..!!
Simply wrapping "(something)" in a italic tag ?
var list=document.getElementsByTagName('ul')
list[0].firstChild.nextSibling.childNodes[0].firstChild.nodeValue = "one<i>(something)</i>")
You can do it with .innerHTML and and an <i>:
var list=document.getElementsByTagName('ul');
var p = list[0].firstElementChild.firstElementChild;
p.innerHTML = "one<i>(something)</i>";
You can use jQuery to handle this problem easily. The code will be:
$("ul li p:first").html("one<i>(something)</i>");
That means take the first p tag within a li html tag in the ul and change its html content to one<i>(something)</i>. I have made a Plunker demo for you.
Be careful, because this code will replace all the first elements in your lists on your web page, where it has a p tag. To avoid that, you can assign to your desired ul a class. For example the list in your code has already have a class called q, so the code will look like:
$(".q :first").html("one<i>(something)</i>");
EDIT: To get a specific child(not absolutely the first) you can use :nth-child(<number of child>) insted of :first. For demos look at the jQuery documentation.

jQuery: Best way to append to html of a paragraph inside a textarea

I have a textarea that contains variable html content which is always wrapped in a paragraph (p) tag.
HTML (before appending):
<textarea rows='7' class='form-control' id='comments'><p>My variable HTML content.</p></textarea>
I fetch this content using the following in jQuery:
jQuery:
$('#comments').val();
Now I need to append HTML at the end of this paragraph but inside the p tag.
HTML (after appending):
<textarea rows='7' class='form-control' id='comments'><p>My variable HTML content. Some appended HTML.</p></textarea>
I can of course replace the last 4 characters of the above (which is the closing p tag), then append my HTML and then add the closing p tag again.
Can someone tell me if there is a better way to achieve the same in jQuery ?
Many thanks in advance for this, Tim.
Parse the string value of the textarea as HTML, and insert whatever you like, then pass the string value of the HTML back
$('#comments').val(function(_, val) {
return $('<div />', {html:val}).find('p').append('content').end().html();
});
FIDDLE
This could do the trick
var html = $('#comments').val();
$('#comments').val(
$(html).append(' Some appended HTML.')[0].outerHTML
);
DEMO
You could insert the value into a temporary div, add an element to the <p>-element inside the temporary div and fetch the renewed content again:
var tmpDiv = $('<div></div>'); //create temporary element
tmpDiv.html($('#comments').val()); // add HTML from textarea
$(someHtml).appendTo($('p', tmpDiv)); // append custom HTML to P inside temp element
newTextAreaValue = tmpDiv.html(); // retrieve new value
Ok. I REALLY love this!
$('#comments').text($($('#comments').text()).append(' a new insert!').text());
Don't look at it too long. Could hurt your eyes :-)

HTML DOM manipulation : properly replace tag by heading tag

I want to replace some tag-inside-a-paragraph-tag by a heading-tag-enclosed-by-a-paragraph tag. This would result in proper W3C coding, but it seems that jQuery is not able to manipulate the DOM in the right way!? I tried several ways of (jQuery) coding, but i can't get it to work ..
Original code:
<p>some text <span>replace me</span> some more text</p>
Desired code:
<p>some text</p><h2>my heading</h2><p>some more text</p>
Resulting code by jQuery replaceWith():
<p>some text<p></p><h2>my heading</h2><p></p>some more text</p>
Demo: http://jsfiddle.net/foleox/J43rN/4/
In this demo, look at "make H2 custom" : i expect this to work (it's a logical replace statement), but it results in adding two empty p-tags .. The other 2 functions ("make code" and "make H2 pure") are for reference.
Officially the W3C definition states that any heading tag should not be inside a paragraph tag - you can check this by doing a W3C validation. So, why does jQuery add empty paragraph tags? Does anybody know a way to achieve this? Am i mistaken somehow?
You can achieve this with this code. However it's pretty ugly:
$('.replaceMe').each(function() {
var $parent = $(this).parent(),
$h2 = $(this).before('$sep$').wrap('<h2>').parent().insertAfter($parent);
var split = $parent.html().split('$sep$');
$parent.before('<p>' + split[0] + '</p>');
$h2.after('<p>' + split[1] + '</p>');
$parent.remove();
});
http://jsfiddle.net/J43rN/5/
If you read the jQuery docs, you will find:
When the parameter has a single tag (with optional closing tag or
quick-closing) — $("<img />") or $("<img>"), $("<a></a>") or $("<a>")
— jQuery creates the element using the native JavaScript
createElement() function.
So that is exactly what it is doing. And as I said in my comment, you can't change a parent node from a child node, you're altering the DOM here, not HTML code. So you'll need to either use replaceWith on the parent node and replace everything or use something like remove and append to split it up in multiple elements which you append after each other.
Try this:
var temp = "<p>some text <span>replace me</span> some more text</p>";
temp.replace(/(\<span\>replace me\<\/span\>)/gi, '</p><h2>my heading</h2><p>');
This will do a case insensitive replace for multiple occurences as well.
Read more about capturing groups here
Original credit to this question!
Please try this I have updated the http://jsfiddle.net/J43rN/6/ example by the below java script function please check I hope it will work for you
function fnMakeCode() {
$('#myP #replaceMe').html("<code id='replaceMe'>My Code</code>");
}
function fnMakeH2pure() {
$('#myP #replaceMe').html("<h2 id='replaceMe'>My H2 pure</h2>");
}
function fnMakeH2custom() {
$('#replaceMe').html("<p></p>").html("<h2>My H2 custom</h2>");
}

Javascript/jquery replace text removes formatting of div

http://jsfiddle.net/2EvGF/
JS
$('.msgln').each(function() {
var text = $(this).text();
$(this).text(text.replace('Admin', 'sys-admin'));
});
HTML
<div class='msgln'><b>Admin</b>:<i> Chat cleared</i><br></div>
Replacing the class '.msgln' removes the formatting (bold, italics, etc.) How can I resolve this?
It might be happening because the css rules for bold, italcs etc might be defined for the class msgln, so once the class is removed the associated css rules also will be removed.
A solution is to add another class where the same css rules are defined
As it said here, http://api.jquery.com/text/#text2, it replace whole inner html with the given text.
You need to get down to the element that has the text you want to replace. In your case, it would be .msgln b
$('.msgln b').each(function() {
var text = $(this).text();
$(this).text(text.replace('Admin', 'sys-admin'));
});
I agree with sincebasic's solution. Here's my version with little update as you can have tag presented in other parts of the the HTML with the class "msgln". How about the following?
HTML
<div class='msgln'><b><span class="username">Admin</span></b>:<i> Chat cleared</i><br></div>
JS
$('.msgln span.username').each(function() {
var text = $(this).text();
$(this).text(text.replace('Admin', 'sys-admin'));
});

Categories