get innerHTML from DOM using cheerio - html

This Meteor server code tries to extract the innerHTML from a html string using cheerio package but the error says that the elements has no method 'size'
What am I doing wrong and how to fix it? Thanks
here is the html;
<span class='errorMsg'>some text </span>
message: (html, typeMsg) => {
let $ = cheerio.load(html);
const selection = 'span.' + typeMsg;
const elements = $(selection);
return elements.size() > 0 ? elements.get(0).innerHTML.trim() : '';
}

After few trials and errors and trying to understand the docs, which cloud benefit from some more explanations.
Option 1
const element = $(selection).eq(0);
return element ? element.text().trim() : '';
Option 2
const element = $(selection).get([0]);
return element ? element.children[0].data.trim() : '';
I used option 1 in this case.

var cheerio = require('cheerio');
var $ = cheerio.load('<b>hello</b> world');
// innerHTML
$('body').html()
// <b>hello</b> world
// outerHTML
$.html($('body'))
// <body><b>hello</b> world</body>
// innerText
$('body').text()
// hello world
docs: https://api.jquery.com/html/#html1

My HTML looked like this:
<div class="col-xs-8">
<b>John Smith</b><br />
<i>Head of Widgets</i><br />
Google<br />
Maitland, FL<br />
123-456-7890<br />
<a
href="mailto:example#example.com"
>example#example.com</a
>
</div>
I wanted to extract the inner html of the div in the context of an "each" loop, so I used this code:
$(this).html()
Which returned
<b>John Smith</b><br />
<i>Head of Widgets</i><br />
Google<br />
Maitland, FL<br />
123-456-7890<br />
<a
href="mailto:example#example.com"
>example#example.com</a
>

Related

How to get a div's text value with react testing library?

<a className="stats__back" href="./..">
🠔
</a>
<div className="profile-heading">ACCOUNT</div>
<div className="profile-header">
<div className="profile-avatar">
<img className="account-avatar" src={`./images/avatar${avatar}.png`} alt="User's avatar" width="150" height="150" />
</div>
<div className="profile-header-info">
<div className="profile-username">{userName}</div>
<div className="profile-creation-date">
This is the part of the code I'm working on, and I'm trying to get access to div with className="profil-username" for unit test.
Here is how my test looks:
test('New user name is set after user name edition.', () => {
act(() => {
ReactDOM.render(<Account/>, container);
});
let profileUserName = container.querySelector("div.profile-username");
let editButton = container.querySelector('.edition-text');
let editUserName = container.querySelector('.account_modal-nick-input');
let okButton = container.querySelector('.modal-button-save');
let newUserName = "newUserName";
fireEvent.click(editButton);
fireEvent.change(editUserName, {target: {value: newUserName}});
fireEvent.click(okButton);
expect(profileUserName.value).toBe(newUserName);
});
So generally speaking I'm totally new to react and generally unit tests, and my final question is: How to get this particularry div using querySelector and how to call his value after this, is this just by writing divContainerVariableName.value or something else
Thank you in advance
const profileUserName = container.querySelector("div.profile-username");
expect(profileUserName.textContent).toBe(newUserName);
If you have more than one .profile-username, it will get the first one appears in the dom tree.
You should first check if you have targeted the correct dom element first, then consider getting it's text context.

React Render HTML object from JSON object

I have to render html object Array in React JS
Can anyone guide me how to use renderHTML function.
output of the object is something like this:
"
const items = this.state.Data.map(item => (
<div key={item._id}>{renderHTML("{item.albComEn}")}</div>
another variation i tried
const items = this.state.Data.map(item => (
<div key={item._id}>{renderHTML("item.albComEn")}</div>
));
output i get => "item.albComEn"
or
{item.albComEn}
You can try with template strings. More info
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
const items = this.state.Data.map(item => (
<div key={item._id}>{renderHTML(`${item.albComEn}`)}</div>
You can also use short syntax of React Fragments i.e. '<> </>'. Use these to bracket to write the html code. When rendered the html code will successfully compiled.
Example:
const service = [
{
htmlCode: <>
<div>
<h2>Application Screening</h2>
<br />
<br />
What you can expect from us:<br />
- Your resume will be written by a team of seasoned experts<br />
- They will make sure that your Resume presents your strong points,
achievements & key skills in a recruiter-friendly format.<br />
</div>
</>
},
]
Use inside render method as
...
render(
<div>
{service[0].htmlCode}
<div>
)
}

How to embed an external widget to a page in Bolt?

I'm trying to embed a booking system widget to my bolt homepage (the one and only homepage, using base-2018 theme). I paste it into the Content window, selecting Source first. Bolt seems to interpret what is going on, as various tags and IDs are highlighted in the code.
The widget code is roughly so:
<div id="bokun [blabla]">Loading...</div>
<p><script type="text/javascript"><br />
var w15;<br />
(function(d, t) {<br />
var host = 'widgets.bokun.io';<br />
var frameUrl = 'https://' + host + '/widgets/15';<br />
var s = d.createElement(t), options = {'host': host, 'frameUrl': frameUrl, 'widgetHash':'w15', 'autoResize':true,'height':'','width':'100%', 'minHeight': 0,'async':true, 'ssl':true, 'affiliateTrackingCode': '', 'transientSession': true, 'cookieLifetime': 43200 };<br />
s.src = 'https://' + host + '/assets/javascripts/widgets/embedder.js';<br />
s.onload = s.onreadystatechange = function() {<br />
var rs = this.readyState; if (rs) if (rs != 'complete') if (rs != 'loaded') return;<br />
try {<br />
w15 = new BokunWidgetEmbedder(); w15.initialize(options); w15.display();<br />
} catch (e) {}<br />
};<br />
var scr = d.getElementsByTagName(t)[0], par = scr.parentNode; par.insertBefore(s, scr);<br />
})(document, 'script');<br />
</script></p>
I have only edited out the unique ID this widget has. Otherwise, this is copied from the provider and works on my current Wordpress site...ALTHOUGH when I paste it into Wordpress, the editor notifies me that "there's something wrong" and offers me to correct it.
How do I insert this? Do I need to create a .js file and reference it in compliance with Twig standards and if so, how do I? I should also note that the widget will redirect to a different page within the same site once you press something within it. Thank you.
Bolt version: 3.6.5
You need to add every tag and attribute that you need into the `config.yml.

How to hide some text in string using CSS

Please find updated code
<html>
<title>css</title>
<head>
<style>
#st {
z-index: -114;
margin-right: -80px;
}
</style>
</head>
State Code : <span><span id="st"></span>Maharashtra - MH</span>
</html>
I got below output but i need clear overlapped text
enter image description here
the only way to approach this is using css display: none or visibility: hidden property , either one would work, i would advice display none. this is the only way CSS and HTML can hide data.
<span>State Code: <span id="st"><span style="display: none">Maharashtra - </span>MH</span></span>
You Can't do this by using CSS only here is the javascript solution for u
$("#st").html(function(){
var text= $(this).text().trim().split(" ");
var first = text.shift();
return (text.length > 0 ? "<span class='hide'>"+ first + "</span> " : first) + text.join(" ");
});
.hide {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>State Code: <span id="st">Maharashtra - MH</span></span>
see this is HTML version but it is working fine.
<span id="span_Id">Maharashtra - MH</span>
<script>
function getSecondPart(str) {
return str.split('-')[1];
}
var span_Text = document.getElementById("span_Id").innerText;
var html = getSecondPart(span_Text);
document.getElementById("span_Id").innerHTML = html;
</script>
Update 2
Layout has significantly changed...see 2nd updated demo.
Since OP has dynamically generated text, JavaScript is needed realistically. And probably the actual text will be more than one on the page.
This demo gathers all <span> nested within a <span> (could've used #id but realistically, it should be a .class). This NodeList is converted into an array.
This array is then map()'ped on each iteration a regex is matched vs. the <span>s text.
A replace()'ment of the unwanted portion of text is overwritten and the last 2 letters remain.
Demo
var tgt = Array.from(document.querySelectorAll('span'));
tgt.map(function(s, idx) {
var str = s.textContent;
var rgx = /(State Code:).*?- (\w\w)/g;
var rep = `$1 $2`;
var res = str.replace(rgx, rep);
s.textContent = res;
});
<span>State Code: <span class="st"></span>California - CA</span><br>
<span>State Code: <span class="st"></span>New York - NY</span><br>
<span>State Code: <span class="st"></span>Oregon - OR</span><br>
<span>State Code: <span class="st"></span>Mississippi - MS</span><br>
If you use PHP... try it below..
$string = explode("-","Maharashtra - MH");
<span>State Code: <span id="st"><span style="display:none;"><?php echo $sting[0]."-"; ?></span><?php echo $string[1]; ?></span></span>

split string of spans into array of spans

I have a block of text wrapped in spans that I need to split into an array.
So currently I have
var s = `
<span class="hoverable">c</span>
<span class="hoverable">o</span>
<span class="not-hoverable">o</span>`;
I need
var s = [
"<span class="hoverable">c</span>",
"<span class="hoverable">o</span>",
"<span class="not-hoverable">o</span>"];
I've tried s.split(/<\/?span>/); to split accounting for <span> and closing </span> but
var s = [
"<span class="hoverable">c",
"<span class="hoverable">o",
"<span class="not-hoverable">o",...]
So it's not including the closing span.
As always when a regexp question wanders over into HTML or XML territory, I suggest regexp is not the right tool. Use the proper HTML parser available in the language you are using. In case of JavaScript (implied by your use of var and string template syntax):
let s = `
<span class="hoverable">c</span>
<span class="hoverable">o</span>
<span class="not-hoverable">o</span>`;
let d = document.createElement('div');
d.innerHTML = s;
let result = Array.from(d.children).map(e => e.outerHTML);
console.log(result);
You can always use the DOM if you are working in a browser and the value is inside of an element. If it is not and you have a string then you can still use DOM dynamically. Finally, you can use regular expressions.
Here's a round up:
var s = ' ' +
'<span class="hoverable">c</span>' +
'<span class="hoverable">o</span>' +
'<span class="not-hoverable">o</span> ';
var r2 = s.match(/<span(.*?)>(.*?)<\/span>/gm);
console.log("using regular expressions");
console.log(r2);
function findWithDOM() {
console.log("using DOM");
var elements = [].slice.call(document.querySelectorAll('#myDiv span'));
console.log(elements);
}
function findWithDynamicDOM() {
console.log("using Dynamic DOM");
var element = document.createElement("div");
element.innerHTML=s;
var elements = [].slice.call(element.querySelectorAll('span'));
console.log(elements);
}
<div id="myDiv"><span class="hoverable">c</span>
<span class="hoverable">o</span>
<span class="not-hoverable">o</span>
</div>
<input id='btnFind' onclick='findWithDOM()' value='Find With DOM' type="button" />
<input id='btnFind' onclick='findWithDynamicDOM()' value='Find Dynamic DOM' type="button" />