Conversion of html object to string failed using jquery - javascript

Tried to convert my parsed html object to string but it returned only the title. Would appreciate some input in this regard
var html = `<html><title>My title</title><head></head><body><h1>hello World</h1></body></html>`;
html = $.parseHTML(html);
//do something here
//after parse to object, revert back to string
htmlString = $(html).prop('outerHTML'); //this is not working
console.log(htmlString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

try
var _html = `<html><title>My title</title><head></head><body><h1>hello World</h1></body></html>`;
_html = $(_html);
htmlString = $('<div></div>').append(_html).html() ; //this should work
console.log(htmlString)
;

I would create a new element, then append the html to it and finally print the html of the new element.
Try this:
var html = `<html><head><title>My title</title></head><body><h1>hello World</h1></body></html>`;
var fake_html = $( document.createElement('html'));
fake_html.html(html);
//As jQuery object, you can do whatever you want with this fake_html (here I just change the Title string)
fake_html.find('title').html("Title changed");
htmlString = fake_html.prop('outerHTML');
console.log(htmlString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

How can I add data params to an HTML string and get a string back?

I got a string like this:
var select_string = '<select><option>1</option><option>2</option></select>';
I need to add some data params to select in this string and get this string back in order to get the following:
select_string = '<select data-param1="param1" data-param2="param2"><option>1</option><option>2</option></select>';
I tried to use jQuery functions like .html() or .text() but it did not work. Like this:
select_string = $(select_string).data('param1', 'param1').html() //or .text()
Any ideas how to make it work would be helpful. Thank you.
You can use attr to add that attributes to the element
var select_string = '<select><option>1</option><option>2</option></select>';
var select = $(select_string).attr({
'data-param1': 'param1',
'data-param2': 'param2'
});
console.log(select.prop('outerHTML'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Since your attribute name starts with data-, if you want to get the value, you can use:
select.data('param1'); // param1
select.data('param2'); // param2
EDIT: Titulum is right, jquery is not needed here.
But here is the working example usign jquery
var selectString = '<select><option>1</option><option>2</option></select>';
var $select = $(selectString);
$select.attr("prop_key","prop_value");
var selectChanged = $select.prop('outerHTML');
console.log(selectChanged)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You don't need jQuery for this:
const myElement = document.createElement('div');
myElement.innerHTML = "<select><option>1</option><option>2</option></select>";
const selectElement = myElement.getElementsByTagName("select")[0];
selectElement.setAttribute("data-param1", "param1");
selectElement.setAttribute("data-param2", "param2");
You could use indexOf and substr() to split it into 2 parts, insert your new text, and put it back together again.
var first_half = select_string.substr(0, select_string.indexOf('>'));
var second_half = select_string.substr(select_string.indexOf('>'));
select_string = first_half + ' data-param1=\"param1\" data-param2=\"param2\" ' + second_half;

extract text values from a string like html

I have this string (not html but string):
<div class="rTag">ATINA</div><div class="rTag">BELMOPAN</div><div class="rTag">DAMASK</div><div class="rTag">FILIPINI</div><div class="rTag">BANGKOK</div>
Need to extract text value of rTag so result should be a new string:
ATINA,BELMOPAN,DAMASK,FILIPINI,BANGKOK
Any help?
This will set the content of #output to the new str, but you can do whatever you want after its joined.
var str = [];
var content = '<div class="rTag">ATINA</div><div class="rTag">BELMOPAN</div><div class="rTag">DAMASK</div><div class="rTag">FILIPINI</div><div class="rTag">BANGKOK</div>';
var $html = $($.parseHTML("<div>" + content + "</div>"));
$html.find(".rTag").each(function(){
str.push($(this).html());
});
$("#output").html(str.join(","));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div id="output"></div>
Parsing an HTML string into a DOM element so that it can be processed by javascript/jquery is a fairly standard process:
$(content)
will suffice without needing to add it to the DOM (and all that entails behind the scenes).
In this case:
var content = '<div class="rTag">ATINA</div><div class="rTag">BELMOPAN</div><div class="rTag">DAMASK</div><div class="rTag">FILIPINI</div><div class="rTag">BANGKOK</div>';
var arr = $(content).filter(".rTag").map(function() {
return $(this).text();
}).get();
console.log(arr.join(","));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

javascript find div id inside string and delete it's content

I have a string with some variable html saved inside, among which a div with static id="time",
example:
myString = "<div class="class">blahblah</div><div id="time">1:44</div>"
How can I create a new identical string cutting off only the time? (1:44 in this case).
I can't look for numbers or the ":" because is not safe in my situation.
What i've tried without success is this:
var content = divContainer.innerHTML;
var jHtmlObject = jQuery(content);
var editor = jQuery("<p>").append(jHtmlObject);
var myDiv = editor.find("#time");
myDiv.html() = '';
content = editor.html();
console.log('content -> '+content);
var myString = '<div class="class">blahblah</div><div id="time">1:44</div>';
//create a dummy span
//put the html in it
//find the time
//remove it's inner html
//execute end() so the jQuery object selected returns to the span
//console log the innerHTML of the span
console.log($('<span>').html(myString).find('#time').html('').end().html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can achieve this using a regular expression in plain javascript like so:
myString.replace(/(<div id="time">).*(<\/div>)/, '$1$2')
If you want to extract only the 1:44 portion you can use the following:
myString.match(/(<div id="time">)(.*)(<\/div>)/)[2]

convert raw string source to html to use jquery selector

I have this source
<div class="page"><h1>First Page </h1></div>
How can I convert it to html and use selector like $('.page') ? I tried to assign above string to a variable then use html() it doesn't work.
You can parse your string in HTML, after that if you look the object returned, there's a data property on the first row who contain the html string with good format.
EDIT
You can get HTML object properties without append it to the DOM. Check my edited code.
var test = '<div class="page"><h1>First Page </h1></div>';
var testHTML = $.parseHTML(test);
var elemHTML = $(testHTML[0].data);
console.log(elemHTML.text());
You can try this :
var test = '<div class="page"><h1>First Page </h1></div>';
var testHTML = $.parseHTML(test);
$("body").html(testHTML[0].data);
$(".page").css("color","blue");
//Without append element in the DOM
var elemHTML = $(testHTML[0].data);
console.log(elemHTML.text());
//For count number of element you can use a container without append it to the DOM
var container=$("<div></div>");
container.append(elemHTML);
console.log(container.find(".page").length);
.page{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
See comments, first we have to process the entities, then use the result as HTML:
// The string
var str = '<div class="page"><h1>First Page </h1></div>';
// A wrapper element to put it in
var wrapper = $("<body>");
// Process the character entities
wrapper.html(str);
str = wrapper.text();
// Convert the resulting HTML to a structure
wrapper.html(str);
console.log("Text of .page: ", wrapper.find(".page").text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
That's verbose for clarity; here's the concise version:
var str = '<div class="page"><h1>First Page </h1></div>';
var wrapper = $("<body>");
wrapper.html(wrapper.html(str).text());
console.log("Text of .page: ", wrapper.find(".page").text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use following script for this
$('.page').html('<div class="page"><h1>First Page </h1></div>');
or
var htmlString = '<div class="page"><h1>First Page </h1></div>';
$('.page').html(htmlString);
Jquery automatically convert it to html

Get specific value from a HTML output

I am getting the following result from a data source.
"<span class=\"highlight\">DSDT10</span><div>011XBY</div>"
The value in span and div could vary.
And I want only the value inside the span "DSDT10" in a separate variable.
What I have tried:
var data = '<span class=\"highlight\">DSDT10</span><div>011XBY</div>';
var formattedData = data.replace(/<\/?span[^>]*>/g, "");
$('#output').append(formattedData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>
Expectation:
Retrieve only "DSDT10" from the data variable.
Any suggestion is appreciated. Thanks.
You just want to get the text within the span? You could modify your regex a bit and use a match..
var data = '<span class=\"highlight\">DSDT10</span><div>011XBY</div>';
var formattedData = data.match(/<span[^>]*>([^<]*)<\/span>/, "")[1];
But since you're using jquery you could also just do this:
var formattedData = $("<div>", {html: data}).find("span").text()
Only two lines of code:
_str = "<span class=\"highlight\">DSDT10</span><div>011XBY</div>";
_span = $(_str).filter('span').text();
It's enough only one line:
$('#output').html($('span').html());

Categories