How to detect clickable link in HTML - javascript

I am getting a response in a list from backend and putting error codes to a table as in picture
This explanation string has a URL in it as you see www.google... I want to make it clickable but I cannot.
When I try to replace the link with regex with following codes (my model object for the table item is response: errorArray.slice(1, errorArray.length));
const urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
const errorArray = errorResponse.error.toString()
.replace(/\[/g, "")
.replace(/]/g, "")
.replace(urlRegex, "<a href='$1' target='_blank' ></a>")
.replace(/\.,/g, ".")
this.allUploadedPinsFiles.push({uploadDate: uploaded, fileName: file.name,
status: status, responseHeader: errorArray[0], response: errorArray.slice(1, errorArray.length)});
It becomes
It is replacing item in the error array but in UI it still shows as a text. How can I make it that it can understand the link in a text and make it clickable?
and here is the html code for that list:
<div *ngIf="upload.response.length > 0">
<ul class="list-item">
<li *ngFor="let singleResponce of upload.response">{{singleResponce}}</li>
</ul>
</div>

Sanitize the data and pass to the html
this.sanitizer.bypassSecurityTrustHtml("<a href='www.google.com' target='_blank'>My Link</a>)
Try this
Working link

Use innerHtml
<li *ngFor="let singleResponce of upload.response">
<span [innerHtml]="singleResponce"
</li>

Related

Get href list under HTML content

I have a json string which contains HTML element. What I am trying to achieve is to fetch all anchor tag value <a> in that string.
Json String
"content" : "<p>Reference information</p> <ul> <li>My Url</li> <li>Your Url</li> </ul>"
Here is HTML Format
<p>Reference information</p>
<ul>
<li>My Url</li>
<li>Your Url</li>
</ul>
I have tried like this but cannot get exact value:
<div id="TestDiv" hidden >
</div>
let anchor = document.getElementById("TestDiv").getElementsByTagName("li");
anchor[0].innerHTML
I am getting this value
My Url
But I want to get https://myurl.com
another way I tried which was closed though still has problem but don't want to use regex:
content.match(/href="([^"]*?)"/);
How can I achieve that?
// Create an element
const el = document.createElement("div");
// set the inner HTML
el.innerHTML = `
<p>Reference information</p>
<ul>
<li>My Url</li>
<li>Your Url</li>
</ul>
`;
// grab all <a> tag
const nodeList = el.querySelectorAll("a");
// convert to array
const nodeArray = [...nodeList];
// map to href
const hrefs = nodeArray.map((a) => a.href); // ["https://myurl.com/", "https://yoururl.com/"]
You can use Array.prototype.map like:
var anchorUrls = Array.prototype.map.call(
document.anchors, (i) => i.href;
);
console.log(anchorUrls);
You can access the href attribute value using .href or using the getAttribute("href") method. However you are currently getting the li elements, but you want to instead get the anchor elements.
let anchor = document.getElementById("TestDiv").getElementsByTagName("a");
anchor[0].href;
To get all of the href's you will need to loop through the array of anchors.
var i;
for (i = 0; i < anchor.length; i++) {
anchor[i].href;
}

Create a clickable list in HTML using JSON data with Javascript

I'm using Jquery mobile, and I want to create a clickable view list in my panel. to look something like this...
<li><a href='#' onclick='getmoviepic_mobile(this) ;' > MovieTitle"</a>
</li>
MovieTitle is obtained from my MYSQL database array using json_encode($x) so when the user clicks on the title the function getmoviepic_mobile(this) is triggered.
My question is how to set up my javascript with json data to populate my html
page.
My HTML
<div data-role="panel" id="Panelcategory" >
<ul data-role="listview" data-inset="true" id="MovieTitle">
<li></li>
</ul>
</div >
PHP getcatagories2_mobile.php
<?php
include("includes/connection.php");
$q=$_POST['input'];
$resultActor = mysqli_query($con,"SELECT id,title,
plot,catagory,release_date,rated FROM ".TBL_DATA." WHERE catagory LIKE
'%".$q."%' ORDER BY title ");
while($rowMovie = mysqli_fetch_array($resultActor)) {
$x[]=$rowMovie['title'];
}
$jsonarray=json_encode($x);
echo $jsonarray;
?>
Javascript
function getcatagories(catagory){
var catagoryValue = $(catagory).text();
$.getJSON( "getcatagories2_mobile.php", {input:catagoryValue},
function(json) { this is the part I am stuck on
}
not sure even if my HTML is set up correctly maybe don't need the "li".
thanks guys
I would iterate through the JSON and add attributes by key. For example, you could query the list and add each value.
$("#MovieTitle").append("<li>" + json["category"] + "</li>")
And do so for each key-value pair you want to include.

How to remove html tags from text in angular 2

I am working with rss feed and got rss feed from my server so i am sending stringfy data but when i bind this in my angular 2 application it shows text with html tags so how we can remove this tags. I just want to show text only.
Here is server code:
exports.newspage=function(req,resp){
db.executeSql("select header,text,teaser from news_d",function(data,err){
if(err){
resp.writeHead(200,{"Content-Type":"text/html"});
resp.write("<html><head><title>500</title></head></html>");
}
else{
resp.writeHead(200,{"Content-Type":"x-application/json"});
resp.write(JSON.stringify(data));
}
resp.end();
});
};
app.get('/newspage', function(req, resp) {
emp.newspage(req,resp);
});
service.ts:
gettagesnews(){
let headers = new Headers();
headers.append('x-access-token',this.token);
var options = new RequestOptions({headers: headers});
return this.http.get('http://services.com:9000/newspage/',options).map((res:Response) => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}
news.ts:
tagesnews:Array<TagesnewsList>;
this.newsauth.gettagesnews().subscribe((dailynews)=>{
this.tagesnews=dailynews;
});
html:
<div *ngFor="let daily of tagesnews">
<span style="font-size: 13px">{{daily.text}}</span> </button>
</div>
i got response with some like this:
sample text
You just need to bind html:
<div *ngFor="let daily of tagesnews">
<span style="font-size: 13px" [innerHTML]="daily.text"></span>
</div>
All of the [innerHTML] answers have the content of the HTML actually rendered... so images are loaded, etc. well if you don't want that, and just the text... you can use a conversion method like this:
stripHtml(html: string) {
var div = document.createElement("DIV");
div.innerHTML = html;
let cleanText = div.innerText;
div = null; // prevent mem leaks
return cleanText;
}
Use replace method with regx to remove the unwanted patterns from the content.
content.replace(/<[^>]*>/g, '\n')
There are two ways to handle it.
1) use the innerHTML tag in your html file
like this =
<div>
<pre [innerHTML]="description"></pre>
</div>
here, description is field which hold the data with html tags(<div>hi<br></br></div>)
2) Second way is that convert your html tags data in plain string then bind with respective form control.
like :- formData['description'] = formData['description'].replace(/<[^>]*>/g, '');

Unable to access span inside an li element?

I am making a simple web app. In one part of it, I have:
<ul class="sortable list-group">
<li id="firstTag" class="tags list-group-item">
<span id="present-count" class="badge"></span>
</li>
I have to access both the li element with id="firstTag" and the span element with id="present-count".
Anyhow, I am able to access only one, if I remove the id="firstTag", I am easily able to acess the span, anyhow, in presence of it, js gives the error: "cannot set property "innerHTML" of null" for the statement:
document.getElementById("present-count").innerHTML = something;
EDIT:
Both are being called in window.onload function with "firstTag" called before "present-count". See this fiddle: http://jsfiddle.net/poddarrishabh/2xzX6/3/
This is what I want the output to look like:
where both the "Present" text and the number can be changed.(I am using bootstrap).
$("#firstTag #present-count").html();
add jquery file to your page and try this
Sounds like you want to create a text node:
var textNode = document.createTextNode("first");
document.getElementById("firstTag").appendChild(textNode);
document.getElementById("present-count").innerHTML = "something";
Or to put the text before the span:
var textNode = document.createTextNode("first");
var present = document.getElementById("present-count");
present.innerHTML = "something";
document.getElementById("firstTag").insertBefore(textNode, present);
Here is an updated Fiddle.
If you are just trying to put some text before the present-count span, then just add another span and target that instead of the wrapping li:
<ul class="sortable list-group">
<li id="firstTag" class="tags list-group-item">
<span id="another-tag"></span>
<span id="present-count" class="badge"></span>
</li>
document.getElementById("another-tag").innerHTML = "some text";
document.getElementById("present-count").innerHTML = "some more text";
Try this code snippet
document.getElementById("firstTag").innerHTML = document
.getElementById("firstTag")
.innerHTML
+ "first";
document.getElementById("present-count").innerHTML ="something";
Hope it helps.
Try adding this
document.getElementById("firstTag").innerHTML ='<span id="present-count" class="badge">'
+ '</span>'
+ ' first';
document.getElementById("present-count").innerHTML = 'something';
DEMO
You were getting this error because with the first
document.getElementById("firstTag").innerHTML = "first"
you were replacing the <span>, and your DOM looked like
<ul class="sortable list-group">
<li id="firstTag" class="tags list-group-item">
first
</li>
</ul>
Then you couldnt find the element with id present-count because it wasnt there.

jQuery search for paragraphs containing multiple words

I have an unordered list called test
<ul id='test'></ul>
it is dynamically populated with data via ajax. Each item 'li' is a div containing 'p' paragraphs. Each paragraph contains some information.
Ex:
<li> <div> <p> test </p> </div> </li>
<li> <div> <p> hi how is it going?</p> </div> </li>
<li> <div> <p> not a test</p> </div> </li>
<li> <div> <p> whoa</p> </div> </li>
I also have a search box which i can get a search term from, I use:
var searchTerm = $("#search").val().trim().split(' '); // an array of words searched for
What I am trying to do is find a way to select all 'li' elements which contain all or some of the search words, but I'm not sure how to approach it best.
Currently, I am doing this:
var results = $('p:contains("'+ searchTerm[0] +'")');
to get an exact match on the first term, but I want to search for multiple terms, not just one.
I would want to search for 'test hi' and get back three nodes cause it searches for 'test' and 'hi'.
I also thought of:
var results2 = $('p').filter(function( index ) {
return ( this +':contains("'+ searchTerm +'")' );
});
Anyone point me in the right direction?
You could do some black magic with the selector, like this:
var results = $('p:contains("' + searchTerm.join('"), p:contains("') + '")');
This looks hard, but I'll explain it.
It joins the search terms with "), p:contains(". Then it just adds the missing p:contains(" and ") to the ends of the result string and searches for it.
A combination of $.filter and $.each (or array.forEach, if you don't care about ie8) can also be of use here:
var searchTerms = ["how", "test"];
$('div').filter(function () {
$text = $(this).text();
var found = 0;
$.each(searchTerms, function (index, term) {
found = $text.indexOf(term) > -1 ? found +1 : found;
})
return found;
}).addClass('match');
jsFiddle

Categories