jQuery to manipulate temporary DOM as HTML string - html

I was following up with the solution here jQuery - Insert text inside element of a HTML string
which is quite similar to my problem, but I was not able to make it work.
Problem Definition:
I get some HTML from some external code, which I store into a variable. The HTML is as follows:
<div class="A2_B3" id="A2_B3">
<div class="symptom">Symptom 1</div>
</div>
<div class="A2_B1" id="A2_B1">
<div class="symptom">Symptom 2</div>
</div>
I store this HTML into a variable called "tmp_dom_html".
My job:
(1) Check whether class="A2_B3" has a next div with class="connected". If found, the add myHtml in it.
(2) If class="A2_B3" does not have the next div with class="connected", the append a div with class called "connected" with myHtml into it.
var myHtml = '<p>Bla Bla Bla</p>';
Finally the HTML should look like this:
<div class="A2_B3" id="A2_B3">
<div class="symptom">Symptom 1</div>
</div>
<div class="connected"><p>Bla Bla Bla</p></div>
<div class="A2_B1" id="A2_B1">
<div class="symptom">Symptom 2</div>
</div>
Here is my code and nothing seems to work. Can anybody help me with the problem.
<script type="text/javascript">
var tmp_dom_html = '<div class="A2_B3" id="A2_B3"><div class="symptom">Symptom 1</div></div><div class="A2_B1" id="A2_B1"><div class="symptom">Symptom 2</div></div>';
var new_dom_html = $(tmp_dom_html);
var myHtml = '<p>Bla Bla Bla</p>';
//If the div with class="connected" is found, like this <div class='connected'></div> but without anything isnide it
new_dom_html.find(".A2_B3").next(".connected").append(myHtml);
if(!new_dom_html.find(".A2_B3").next().hasClass(".connected")){
new_dom_html.find(".A2_B3").after("<div class='connected'>"+myHtml+"</div>");
}
alert($(new_dom_html).html());

Use a DOMParser.
const data = new DOMParser().parseFromString(`<div class="A2_B3" id="A2_B3"><div class="symptom">Symptom 1</div></div><div class="A2_B1" id="A2_B1"><div class="symptom">Symptom 2</div></div>`, "text/html");
const selected = $(data.body);
$('.A2_B3', selected).each(function(){
if(!$(this).next().hasClass('connected')){
$(this).after('<div class="connected"><p>Bla Bla Bla</p></div>');
}
})
console.log(selected[0].innerHTML);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related

Search for Longest strings in Multi Blocks [duplicate]

This question already has answers here:
How to get the children of the $(this) selector?
(19 answers)
Closed 5 months ago.
I have 2 blocks of code and search for a longest string in each block appearing on each alert. obviously, wonderful is longest string in the block 1 and beautiful is longest string in block 2.
wonderful should be in first alert and beautiful should be in second alert, but somehow I miss something. Please give me a hand.
Thanks!
$('.parent').each(function() {
longest = "";
$('.child').each(function() {
var textChild = $(this).text();
if (textChild.length > longest.length) {
longest = textChild;
}
});
alert(longest)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
<div class="child">hello</div>
<div class="child">wonderful</div>
<div class="child">world</div>
</div>
<div class="parent">
<div class="child">hello</div>
<div class="child">beautiful</div>
<div class="child">world</div>
</div>
To do what you require you can use map() to build an array of the text content of the .child elements within each .parent, then you can use reduce() to get the longest of them.
Note that you need to output the longest value within the loop. Try this:
$('.parent').each(function() {
let longest = $(this).find('.child').map((i, el) => el.textContent.trim()).get().reduce((a, b) => a.length > b.length ? a : b);
console.log(longest);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
<div class="child">hello</div>
<div class="child">wonderful</div>
<div class="child">world</div>
</div>
<div class="parent">
<div class="child">hello</div>
<div class="child">beautiful</div>
<div class="child">world</div>
</div>
If you want to get the longest values outside of the loop, then I'd suggest pushing them to their own array which you can iterate through as required.

jQuery - Insert text inside element of a HTML string

I store an html string into var HTML, which I get using the following:
var HTML = $('.group').get(0).outerHTML;
The output of HTML using console.log(HTML) is:
<div class="group">
<div class="class1">
Data123...
</div>
<div class="class2">
<!--I want to insert text here -->
</div>
</div>
Now, I want to insert some text inside the div class="class2". I am using the following code:
$(HTML).find('.class2').text("Hello!");
But now the output of HTML using console.log(HTML) is the same old HTML as before. The text "Hello!" did not get inserted. Can anyone help with the solution.
Here is the complete code:
<div class="group">
<div class="class1">
Data123...
</div>
<div class="class2">
</div>
</div>
<script type="text/javascript">
var HTML = $('.group').get(0).outerHTML;
$(HTML).find('.class2').text("Hello!");
console.log(HTML);
</script>
You're updating a temporary DOM element, but that doesn't change the HTML string. You need to save the DOM elements in a variable.
var new_div = $(HTML);
new_div.find('.class2').text("Hello!");
console.log($(new_div).html());

Is it possible to create a sort of HTML object (even using a framework)

I was wondering if it was possible to create a sort of HTML object instead of copy pasting stuff, I thought of doing it via javascript but wondered if there was an easier way to do it (writing html in JS is a bit tedious).
Basically let's say a have a div like that:
<div class ="col">
<div class="Title">
Title
</div>
<div class="Text">
Text
</div>
</div>
Which is the best way, to have some sort of function where you can objectName.create(title, text) or to have a javascript function like Function(title, text) create the element?
You could take the outer element and clone it, change its content and append it back to where you want it. Be advised that this may duplicate ids if your elements should have one.
function createHtml(title, text) {
const el = document.querySelector('.col').cloneNode(true);
el.querySelector('.Title').innerText = title;
el.querySelector('.Text').innerText = text;
document.body.appendChild(el);
}
createHtml("Foo", "Bar");
<div class="col">
<div class="Title">
Title
</div>
<div class="Text">
Text
</div>
</div>
Another option would be to create the element from scratch
function createElement(title, text) {
const el = document.createElement('div');
el.clasName = 'col';
const titleDiv = document.createElement('div');
titleDiv.className = 'Title';
titleDiv.appendChild(document.createTextNode(title));
const textDiv = document.createElement('div');
textDiv.className = 'Text';
textDiv.appendChild(document.createTextNode(text));
el.appendChild(titleDiv);
el.appendChild(textDiv);
document.body.appendChild(el);
}
createElement("Foo", "Bar");
Note that there are many frameworks out there (like angular, react, vue, ...) that would do things like that easier/better.
It is not so bad to write html in js after template literals became a thing in js, you could do something like this
function addCol(title, text){
document.querySelector(".list").innerHTML += `
<div class="col">
<div class="Title">
${title}
</div>
<div class="Text">
${text}
</div>
</div>
`;
}
addCol("hello", "world");
addCol("foo", "bar");
<div class="list"></div>

cheerio / jquery selectors: how to get text in tag a?

I am trying to access links on a website. The website looks like the first code sample and the links are in different div-containers:
<div id="list">
<div class="class1">
<div class="item-class1">
example1
</div>
</div>
<div class="class2">
<div class="item-class2">
example2
</div>
</div>
</div>
I did tried to extract the links with this code:
var list = [];
$('div[id="list"]').find('a').each(function (index, element) {
list.push($(element).attr('href'));
});
But the outputs look like this:
0: "http://www.example.com/1"
1: "http://www.example.com/2"
But I want it to look like this:
0: example1
1: example2
Thank you very much.
$(element).attr('href') ==> get href property : the link
$(element).text() ==> get text
just change like this :
var list = [];
$('div[id="list"]').find('a').each(function (index, element) {
list.push($(element).text());
});

Passing get variables within the page using json

I am trying to pass a get variable within the same html page as the page is created in jquerymobile.js
The html contains various internal pages as provided below. Now i want to pass get variables to other page within the same html as id='page1', id='page2' etc. Can anybody help on how can i pass get or post variable within the same html?
decodeURI(getUrlVars()["type"]) is not working in this case since the data is being passed using id over page (id='page2')
Here is the code:
//Page 1 within the same HTML
<div data-role="page" id="page1">
<div data-role="header" data-theme="b">
<h1>Page1 Header</h1>
</div>
<div data-role="content">
//dynamic server content displayed here
</div>
<div data-role="footer" data-position="fixed" data-theme="b">
</div>
</div>
//Page 2 within the same HTML
<div data-role="page" id="page2">
<div data-role="header" data-theme="b">
<h1>Page2 Header</h1>
</div>
<div data-role="content">
//Want to get some of the individual dynamic content displayed in page1 using get method in JSON
</div>
<div data-role="footer" data-position="fixed" data-theme="b">
</div>
I am trying to pass get variable as Button which is not working.
Use following function to get the parameter value
function getParameterByName(name, url) {
if (!url) {
url = window.location.href;
}
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}