Question
How can I replace a < with an anchor as an HTML wrapper?
Background
I am getting a JSON value with a Twitter user's name as something like
<jgallardo949>
Since i don't want that printed to the page:
i want to replace the < with <a
href="twitter.com/{{data.author}}">
and the > with </a>
The end result in the code will be jgallardo949
The end result on the page will just be: jgallardo949
I referenced other similar questions that I was able to find here and elsewhere. I got a start with the answers on Replace string of text javascript
My followup practice worked. But specifically the > symbol is having a challenge, or i am missing something?
Code
The top two work, the last one does not
HTML
<div class="label">With Profits Financial Strength:</div>
<div class="data rating">****</div>
<div class="data2 thing">+</div>
<div class="author twitter"> > </div>
JS
var str=document.getElementsByClassName("data" ,"raiting")[0].innerHTML;
var n=str.replace(/\*/g,"star");
document.getElementsByClassName("data", "raiting")[0].innerHTML=n;
var str2=document.getElementsByClassName("data2" ,"thing")[0].innerHTML;
var n2=str2.replace(/\+/g,"<h1>moon</h1>");
document.getElementsByClassName("data2", "thing")[0].innerHTML=n2;
var str3=document.getElementsByClassName("author" ,"twitter")[0].innerHTML;
var n2=str3.replace(/\>/g,"<h1>moon3</h1>");
document.getElementsByClassName("author", "twitter")[0].innerHTML=n2;
A > in HTML gets returned as > so doing like this (\>|>) and it will find both.
var n2=str3.replace(/(\>|>)/g,"<h1>moon3</h1>");
Stack snippet
var str=document.getElementsByClassName("data" ,"raiting")[0].innerHTML;
var n=str.replace(/\*/g,"star");
document.getElementsByClassName("data", "raiting")[0].innerHTML=n;
var str2=document.getElementsByClassName("data2" ,"thing")[0].innerHTML;
var n2=str2.replace(/\+/g,"<h1>moon</h1>");
document.getElementsByClassName("data2", "thing")[0].innerHTML=n2;
var str3=document.getElementsByClassName("author" ,"twitter")[0].innerHTML;
var n2=str3.replace(/(\>|>)/g,"<h1>moon3</h1>");
document.getElementsByClassName("author", "twitter")[0].innerHTML=n2;
<div class="label">With Profits Financial Strength:</div>
<div class="data rating">****</div>
<div class="data2 thing">+</div>
<div class="author twitter"> > </div>
Related
I'm using a controller to convert any web links inside an <input> tag, and show them in a <p> tag. I want it to show the links in a hyperlink format as in
https://www.w3schools.com is great but it shows
Here's my code,
my HTML
<div class="col-sm-10 col-sm-offset-1">
<div class="row" style=" margin-top:70px;">
<div id='dv1'>
<form>
<input ng-model="comment.txtcomment" id="txtcomment" style='width:500px' >
<button ng-click="addComment()" style='margin-top:10px;'>Post Comment</button>
</form>
<!--displaying comments-->
<h4>Comments</h4>
<p>{{myText}}</p>
</div>
<div></div>
my controller
(function(){
angular.module('StayFit')
.controller('CommentController',['$scope','$state','$http', function($scope,$state,$http){
$scope.user=JSON.parse(localStorage['User-Data']) || undefined;
console.log( $scope.user.data);
$scope.comment={};
$scope.addComment=function(){
var text=$scope.comment.txtcomment;
//this code will identify any links
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
var text1=text.replace(exp, "<a href='$1'>$1</a>");
var exp2 =/(^|[^\/])(www\.[\S]+(\b|$))/gim;
var val=text1.replace(exp2, '$1<a target="_blank" href="http://$2">$2</a>');
$scope.myText=val;
}//.error(function(error){console.log(error);});
}])}());
Tried using ng-binding-html, also doesn't work
You apparently want to use text as HTML, not text, so you need to use ngBindHtml.
Be aware that SCE comes into play as well, so you will have to use something like $scope.myTextVal = $sce.trustAsHtml(val);.
Please help me to understand this. I have HTML code like this:
<div id="one">
<div>
<div>
<span class="spanone"></span>
<span class="spantwo"></span>
<div>
</div>
</div>
.
.(some other html of the page)
.
<sometag class="spanone"></sometag>
<someothertag class="spantwo"></someothertag>
And I basically want to target only the first <span> and the second by JS without touching the sometags elements. In other words the: <span class="spanone"> and <span class="spantwo">. And then I want to use innerHTML to replace the code with the one I want.
Thanks!
var spanone = document.querySelector('.span1');
var spantwo = document.querySelecftor('.span2');
spanone.innerHTML = "Replacement";
spantwo.innerHTML = "Replacement";
You can achieve this in a couple ways
Use id
<span class="spanone" id="myspan1"></span>
<span class="spantwo" id="myspan2"></span>
so in vanilla JS
var d = document;
d.getElementById('myspan1');
d.getElementById('myspan2');
or with classes
<span class="spanone myspans"></span>
<span class="spantwo myspans"></span>
and in your JS
d.querySelectorAll('.myspans')
This should work:
var spanone = document.querySelector('.spanone')[0];
var spantwo = document.querySelecftor('.spantwo')[0];
I am currently trying to scrape links and thumbnails from this SITE with the help of casperjs. I was able to easily figure out the html structure(shown below). I am trying to extract from all a tags the link found in the href attribute. I run my script but I get an error for video_links . How could I go about scraping all links and thumbnails and output in an array?
Error
TypeError: 'undefined' is not an object (evaluating 'video_links.length')
Script
var casper = require('casper').create({}),video_links,video_thumbnails;
//Functions
function getLinks() {
var element = document.querySelectorAll('.cne-episode-block a');
return Array.prototype.map.call(element, function(e) {
return e.getAttribute('href');
});
}
casper.start('http://video.wired.com/');
casper.then(function() {
video_links = this.evaluate(getLinks);
});
casper.run( this.echo(video_links.length + ' links found.') );
HTML
<div class="cne-thumb-grid-container cne-context-container">
<div class="cne-thumb cne-episode-block " data-videoid="551dc13461646d11aa020000">
<div class="cne-thumb-image cne-rollover" data-powertiptarget="551dc13461646d11aa020000">
<a class="cne-thumbnail cne-zoom-effect js-ajax-video-load" href="/watch/angry-nerd-will-netflix-s-daredevil-fly-or-flop" data-video-series="Angry Nerd" data-video-series-id="518d55c268f9dac897000003" data-video-id="551dc13461646d11aa020000" data-video-categories="[" Movies \u0026 TV "]">
<img class="cne-video-thumb" src="http://dwgyu36up6iuz.cloudfront.net/heru80fdn/image/upload/c_fill,d_placeholder_thescene.jpg,fl_progressive,g_face,h_151,q_80,w_270/v1428076783/wired_angry-nerd-will-netflix-s-daredevil-fly-or-flop.jpg" alt="Will Netflix’s Daredevil Fly or Flop?">
<div class="cne-thumbnail-play">Play</div>
</a>
</div>
<div class="cne-thumb-title the-thumb-title">
<a class="js-ajax-video-load" href="/watch/angry-nerd-will-netflix-s-daredevil-fly-or-flop" data-video-id="551dc13461646d11aa020000">Will Netflix’s Daredevil Fly or Flop?</a>
<div class="cne-thumb-subtitle">
Angry Nerd
</div>
</div>
<div id="551dc13461646d11aa020000" class="cne-thumb-rollover">
<div class="cne-thumb-rollover-box">
<span class="cne-rollover-category"> Movies & TV </span>
<span class="cne-rollover-name"> Will Netflix’s Daredevil Fly or Flop? </span>
<span class="cne-rollover-description"> If Netflix’s new Daredevil series is anything like Ben Affleck’s Daredevil film, we’re all in trouble. Angry Nerd explains what the latest incarnation needs to get right to make sure the man without fear doesn’t turn into a total flop. </span>
</div>
</div>
</div>
</div>
If the selectors are on the same level, you will only need one of them. So just use either cne-thumb or cne-episode-block in your querySelectorAll not both.
I have JSON data that is separated by the day of the week.
If the data was just listed out by just the date's and not in it's own array by day, I'd normally use datatables so that it is filterable. However, I am trying to separate the data so it has headers, like so:
With this json data, I am not sure how I would use data tables to do this and also make it filterable. Does anyone have any suggestions (plugins, etc) that I should use to display the data the way I want in a filterable environment?
This is ultimately how I would like to display the data:
<div id="day_of_week">August 26, 2014</div>
<div id="event">
<span id="time">5:52 AM</span>
<span id="event_name">Page View</span>
<div id="hidden_data">Data: Goes here</div>
</div>
You should use a Templating logic, like #Thimoty suggested, tough implemented manually since you need it to be lightweight. I'm working on a fiddle, I'll post it ASAP.
This is it: http://jsfiddle.net/23e37v18/
HTML
<div id="content">
</div>
<div id="template" style="display: none">
<div class="day_of_week">August 26, 2014</div>
<div class="event">
<span class="time"></span>
<span class="event_name"></span>
<div class="hidden_data"></div>
</div>
</div>
JQuery
var jsonText = '{"August 23, 2014":{"1409069553":{"Data":"Your event"},"1407859953 ":{"Data":"Your event"},"1399911153":{"Data":"Your event"}},"August 24, 2014":{"1409069553":{"Data":"Your event"},"1399911139 ":{"Data":"Your event"},"1399914139":{"Data":"Your event"}},"August 25, 2014":{"1407859953 ":{"Data":"Your event"}}}';
$(document).ready(function(){
var data = JSON.parse(jsonText);
for (var day in data){
$('#content').append(day + '<br/>');
// create block
var blockData = data[day];
var block = $('<div/>').addClass('event_block');
for (var event in blockData){
// your event block
var eventDOM = $('#template .event').clone();
// add content
var date = new Date(event*1000)
// TODO: format date for display
$('.time', eventDOM).append(date);
$('.time', eventDOM).append(blockData[event].Data);
block.append(eventDOM);
}
$('#content').append(block);
}
});
I have this hidden block of code that i want to call based on the values that are received from server:
<div id="hiddenChart" style="display:none;">
<li style="height:auto;">
<div class="col-sm-4" id="chart_0_0">
<div class="panel panel-success" style="width:550px; height:auto;" id="accordion_0_0">
<div class="panel-heading">
<div class="btn-group" style="float:right;">
<i class="glyphicon glyphicon-minus" id="minimize_0_0"></i>
<i class="glyphicon glyphicon-remove" id="close_0_0"></i>
</div>
<h3 class="panel-title">title</h3>
</div>
<div class="panel-body" style="height:400px;">
<nvd3-multi-bar-chart data="Sec1Graf1Data" id="dataChart_0_0" height="400" showXAxis="true" reduceXTicks="true" showYAxis="true" showLegend="true" showControls="true" tooltips="true">
<svg></svg>
</nvd3-multi-bar-chart>
</div>
</div>
</div>
</li>
</div>
but i need to change some values: ids, tags, data variables.
I know how to show the code using "$('ul').append($('div').html());" but i have to change it before doing it.
How can i do it?
How do i define in which fields i have to insert the string i'me receiving?
Thk
UPDATE:
I was able put it to work, here is the fiddle with it fiddle.
When i inspect the element, the ids that i want to change, instead of #1, it returns chart_0_0.
Thank you all for your posts and help
You can get a reference to your div like this:
var $div = $('#hiddenChart');
To clone it,
var $clonedDiv = $div.clone();
Then, in the $cloneDiv object, you make the changes:
$clonedDiv.find(--selector of a node--).attr(atributeName, atributeValue); //change/add attribute
$clonedDiv.find(--selector of a node--).removeAttr(atributeName); //remove attribute
And so on. I won't explain how jQuery works, Lekhnath gave you a link.
Finally you insert the $clonedDiv with .appendTo() wherever you want. The original div remains untouched so you can clone it again and again.
Jquery Change text/html from a hidden div content :
Simple
maintain a copy of the hidden content
replace the content based on the element class/id selector with the server response
then paste the html into another div
replace the content of the hidden back to original (optional)
http://jsfiddle.net/austinnoronha/ZJ3Nt/
$(document).ready(function(){
var serverRes = {
title: "New Title In Header",
body: "New body text from server <\/br><nvd3-multi-bar-chart data=\"Sec1Graf1Data\" id=\"dataChart_0_0\" height=\"400\" showXAxis=\"true\" reduceXTicks=\"true\" showYAxis=\"true\" showLegend=\"true\" showControls=\"true\" tooltips=\"true\"><svg><\/svg><\/nvd3-multi-bar-chart>"
};
var tmpOldCont = $("#hiddenChart").html();
var counter = 1;
$(".serverres").click(function(){
$("#hiddenChart").find(".panel-body").html(counter + " = " + serverRes.body);
$("#hiddenChart").find(".panel-title").text(serverRes.title + " " + counter);
counter++;
$(".box-container").html($("#hiddenChart").html());
$("#hiddenChart").html(tmpOldCont);
});
});