I've got a string of html that I get via $("#datadiv").html();. Within this data are several other elements, and what I would like to do is append some data to one of those elements.
e.g.
var data = $("#datadiv").html();
var somestring = "Some text"
then append somestring into the div #stringholder inside of data. Is this possible?
And before the question comes, no I can't add it to the div before doing $("#datadiv").html();.
You can do something like this:
$(data).find("#stringholder").append(somestring);
As the html method returns a string, you need to pass it into jQuery again to create a jQuery object. You can then call find to get the element you want, and append to append the other string.
jQuery is quite happy to accept a string of HTML as an argument. It's not just selector strings that are accepted. If you pass in a string of HTML, that fragment will be the context for further method calls.
I think you already know this, but note that this will not affect the HTML in the DOM. It will only affect the fragment produced by passing the string into jQuery.
Do you mean :
var data = $("#datadiv").html();
var somestring = "Some text"
var newData = data + " " + somestring;
var holderData = $("#stringholder").html();
var newestData = holderData + " " + newData;
$("#stringholder").html('');
$("#stringholder").html(newestData);
Sure. Basically you could dump the string from the current div in to a variable and then concate the additional text and put it back in the div.
var someText = $('#datadiv').html()
var someNewText = 'my new text'
var someText = someText + ' ' + someNewText
$('#datadiv').html('') //this will clear the current text but not really necessary.
$('#datadiv').html('someText')
you just need to have some event that fires to trigger everything.
Related
I want to find and replace text in a HTML document between, say inside the <title> tags. For example,
var str = "<html><head><title>Just a title</title></head><body>Do nothing</body></html>";
var newTitle = "Updated title information";
I tried using parseXML() in jQuery (example below), but it is not working:
var doc= $($.parseXML(str));
doc.find('title').text(newTitle);
str=doc.text();
Is there a different way to find and replace text inside HTML tags? Regex or may be using replaceWith() or something similar?
I did something similar in a question earlier today using regexes:
str = str.replace(/<title>[\s\S]*?<\/title>/, '<title>' + newTitle + '<\/title>');
That should find and replace it. [\s\S]*? means [any character including space and line breaks]any number of times, and the ? makes the asterisk "not greedy," so it will stop (more quickly) when it finds </title>.
You can also do something like this:
var doc = $($.parseXML(str));
doc.find('title').text(newTitle);
// get your new data back to a string
str = (new XMLSerializer()).serializeToString(doc[0]);
Here is a fiddle: http://jsfiddle.net/Z89dL/1/
This would be a wonderful time to use Javascript's stristr(haystack, needle, bool) method. First, you need to get the head of the document using $('head'), then get the contents using .innerHTML.
For the sake of the answer, let's store $('head').innerHTML in a var called head. First, let's get everything before the title with stristr(head, '<title>', true), and what's after the title with stristr(head, '</title>') and store them in vars called before and after, respectively. Now, the final line is simple:
head.innerHTML = before + "<title>" + newTitle + after;
This might seem a little simple, but i've tried many ways & non of them are working as expected.
i have values coming in from an ajax call, & i am displaying these to a <table>.
the data will not be seen at first (css - display:none) but onclick involves a function which displays a dialog of said data.
writing out the data in these ways does not work:
var text = "Example Data<br>";
var text = document.createTextNode("Example Data" + document.createElement('br'));
var text = document.createTextNode("Example Data");
text += document.createElement('br');
The latter outputs [object Text][object HTMLBRElement]
How do i write this correctly??
You can't concatenate node objects (trying to do so with + will convert them to strings first).
Find the element you want to append the nodes you've created, and call appendChild on it repeatedly.
var text = document.createTextNode("Example Data");
someElement.appendChild(text);
someElement.appendChild(document.createElement('br'));
You need to append the line break as an HTML element "createElement" as it is an HTML element.
var text = 'test';
var newtext = document.createTextNode(text),
p1 = document.getElementById("p1");
p1.appendChild(newtext);
p1.appendChild(document.createElement('br'));
p1.appendChild(document.createTextNode('newline displayed'));
Try
var p = document.createElement("p");
p.innerHTML = "Example Text<br>";
You can try this:
Give the table an id
Append html response to the table by using $('#tableid').html(responsedata);
I want to find and replace text in a HTML document between, say inside the <title> tags. For example,
var str = "<html><head><title>Just a title</title></head><body>Do nothing</body></html>";
var newTitle = "Updated title information";
I tried using parseXML() in jQuery (example below), but it is not working:
var doc= $($.parseXML(str));
doc.find('title').text(newTitle);
str=doc.text();
Is there a different way to find and replace text inside HTML tags? Regex or may be using replaceWith() or something similar?
I did something similar in a question earlier today using regexes:
str = str.replace(/<title>[\s\S]*?<\/title>/, '<title>' + newTitle + '<\/title>');
That should find and replace it. [\s\S]*? means [any character including space and line breaks]any number of times, and the ? makes the asterisk "not greedy," so it will stop (more quickly) when it finds </title>.
You can also do something like this:
var doc = $($.parseXML(str));
doc.find('title').text(newTitle);
// get your new data back to a string
str = (new XMLSerializer()).serializeToString(doc[0]);
Here is a fiddle: http://jsfiddle.net/Z89dL/1/
This would be a wonderful time to use Javascript's stristr(haystack, needle, bool) method. First, you need to get the head of the document using $('head'), then get the contents using .innerHTML.
For the sake of the answer, let's store $('head').innerHTML in a var called head. First, let's get everything before the title with stristr(head, '<title>', true), and what's after the title with stristr(head, '</title>') and store them in vars called before and after, respectively. Now, the final line is simple:
head.innerHTML = before + "<title>" + newTitle + after;
JS Fiddle Example
OK--I have a field that is a full name (last name, first name). The data that is returning isn't last and first name, it is full name. It is then printed last, first. I want to select just the last name (everything before comma), and set it to uppercase.
I may be mixing jQuery and javascript in my example, I'm not positive--still a newb. However, what I've done in the example is to:
function splitLastName(){
var splitNameArray = $('[data-dojo-attach-point|="physcianNameNode"]').split(",");
var lastName = splitNameArray[0];
var firstName = splitNameArray[1];
lastName.wrap('<span class="isUppercase" />');
}
Basically, I'm setting a variable of the field--I've tested that it accurately grabs the element I want it to grab. I'm turning the string into an array, split by the comma field. Then setting the two parts of the array as their own variables. Finally, attempting to wrap the lastName string in a span that adds the 'isUppercase' class. I know I'm doing something wrong, what is it?
function splitLastName(){
$('[data-dojo-attach-point|="physcianNameNode"]').html(function(i, v) {
var names = v.split(',');
return '<span class="isUppercase">' +names[0] + '</span>,' + names[1];
});
}
Fiddle
.html() docs
The above is a quick solution setting a new innerHTML to the element. If you want to use proper DOM manipulation, it'd be like:
function splitLastName() {
$('[data-dojo-attach-point|="physcianNameNode"]').each(function() {
var names = $(this).text().split(',');
$(this).empty().append($('<span>', {
'class': 'isUppercase',
text: names[0]
}), ',' + names[1]);
});
}
Fiddle
Note that I'm using .each() so the code above will work regardless of $('[data-dojo-attach-point|="physcianNameNode"]') matching multiple elements or just a single one.
The problem is you are trying to split a JQuery object.
I have updated your example: See here
function splitLastName(){
var element = $('[data-dojo-attach-point|="physcianNameNode"]');//find the element
var html = element.html();//get the contents of the DIV element
var splitNameArray = html.split(",");//Split the value with comma
var lastName = splitNameArray[0];//store the last name
var firstName = splitNameArray[1];//store the first name
var newHtml = '<span class="isUppercase">' + lastName + '</span>, ' + firstName;//create the new html using the parsed values
element.html(newHtml);//assign the new html to the original DIV element (overwriting the old)
}
The problem occurs with this line:
var splitNameArray = $('[data-dojo-attach-point|="physcianNameNode"]').split(",");
The notation:
$('< some name >')
is a jQuery selector that selects an element. If you type this into your console (replacing < some name > with your selector) in your browser you'll see that it returns an object not a string. So your code is trying to split an object. I don't know where the string is located (div, span, input box etc.) but you need to pull the string to do the split. If your string is text in a div or span use:
var splitNameArray = ($('[data-dojo-attach-point|="physcianNameNode"]').text()).split(",");
as this will grab the string contained in that selector and then perform the split on it. Likewise, if it is in an input you will need to use the proper handler to get the value:
var splitNameArray = ($('[data-dojo-attach-point|="physcianNameNode"]').val()).split(",");
This will pull the value from an input and then perform the split. If your string is in html then you could alternatively grab it using the following notation:
var splitNameArray = ($('[data-dojo-attach-point|="physcianNameNode"]').html()).split(",");
This will pull the html and perform the respective split operation.
Hope this helps.
I have a String which contains HTML tags:
var str = "Hello World <br><p>1</p><em>My First Javascript</em>";
And i also have a form with hidden input:
<input type='hidden' name='id' value=''>
With that String above, i want to get the value inside <p> tag which is 1 and assign that value to hidden input. And after that, i wanted to remove all the HTML tag inside the string which are these <br><p>1</p><em>My First Javascript</em>. So therefore the only value of str will be Hello World.
Is there any way how to do this on Javascript or jquery?
Thanks guys!
So, what you want to be doing is to convert your string into a jQuery object. You can do so like this -
var str = "Hello World <br><p>1</p><em>My First Javascript</em>";
var $holder = $('<div>');
$holder.append(str);
Now we have your string encapsulated within another div element. Next we extract the value within the <p> element -
var value = $holder.find('p').text(); // 1
Now that we have that value we can place it into the hidden input field -
$('input[name="id"]').val(value);
Now to remove all other elements from the original string - we'll use the container we created earlier for this -
$.each($holder.children(),function(index,elem){
$(elem).remove();
});
Now we can take the textual contents of $holder with $holder.text() and it should be just -
Hello World
If you would like to fiddle with this,
you can do so here - http://jsfiddle.net/TVXbw/1/
Ok, a quick and simple way:
var tmpDiv = document.createElement('div');
tmpDiv.innerHTML = str;//where str is the html string, obviously...
var pTagValue = tmpDiv.getElementsByTagName('p')[0].innerHTML;//=== '1'
document.getElementById('yourInputId').value = pTagValue;
If I understood correctly, that's what you're after, right?